I am using spring data backed by hibernate for my project for the CRUD layer and ORM. I was using H2 first. But when switching to SQL server 2014, I faced the following issue:
I use the following service:
#Query("Select example from Example example where
example.exampleProperty like CONCAT('%',:param,'%')")
List<Example> findByProductLibe(#Param("param") String param);
To get Example object (from example table) using a property. It is working well in H2, but moving to sql server (by switching configuration channel AND Dialect to sql server) i have a BadSqlGrammarException due to the query generated by Hibernate is as follows:
Hibernate:
select
ex.param1 as param1,
ex.param2 as param2
from
example ex
where
example.exampleProperty like ('%'||?||'%')
the problem is with the '|' character, it prints 'Incorrect syntax near '|' '
Here is my database configuration:
database.driver = com.microsoft.sqlserver.jdbc.SQLServerDriver
database.password =
database.username =
hibernate.dialect = org.hibernate.dialect.SQLServerDialect
hibernate.ejb.naming_strategy = org.hibernate.cfg.ImprovedNamingStrategy
hibernate.hbm2ddl.auto = create
hibernate.generate_statistics = true
hibernate.format_sql = true
hibernate.show_sql = true
Thanks for any help or indication.
Replace with the below code in repo should work.
#Query("Select example from Example example where
example.exampleProperty like %:param%")
List<Example> findByProductLibe(#Param("param") String param);
Thank you for your answers, The problem is finally resolved, I made my hibernate.dialect to org.hibernate.dialect.SQLServer2012Dialect and it generated the following query:
Hibernate:
select
ex.param1 as param1,
ex.param2 as param2
from
example ex
where example.exampleProperty like ('%'+?+'%')
I must have not cleaned and install the project properly.
Thank you.
Related
I'm developing a Spring Boot application using Spring Data JPA with SQL Server 2017. I want to use LIKE expression to query Khmer Unicode data. SELECT statement I mention below is working fine when I executed it in SQL Server Management Studio
SELECT * FROM merchant_holiday_setting WHERE description_kh LIKE N'%ទិវា%'
But I want to know how to apply it with JPA Specification Criteria here's my code in Spring Boot
override fun findAllList(q: String?, page: Int, size: Int): Page<MerchantHolidaySetting>? {
return mchHolidayRepo.findAll({ root, cq, cb ->
val predicate = ArrayList<Predicate>()
q?.let {
println("Query $q")
val descEn = cb.like(cb.upper(root.get("description")), "%${q.toUpperCase()}%")
val descKh = cb.like(root.get("descriptionKh"), "%$q%")
predicate.add(cb.or(descEn, descKh))
}
predicate.add(cb.isTrue(root.get("status")))
cq.orderBy(cb.asc(root.get<Date>("holidayDate")))
cb.and(*predicate.toTypedArray())
}, PageRequest.of(page, size))
}
Please help me to find out the answer.
Thanks in advance!!
I am using Java-Hibernate with two Databases (Postgresql and MSSQL).
SqlServer2012 with dialect:
hibernate.dialect = org.hibernate.dialect.SQLServer2012Dialect
I have written a Criteria query like :
DetachedCriteria detachedCriteria=DetachedCriteria.forClass(entityClazz);
ProjectionList proj = Projections.projectionList();
proj.add(Projections.max(COMPOSEDID_VERSION_ID));
proj.add(Projections.groupProperty(COMPOSEDID_ID));
detachedCriteria.setProjection(proj);
criteria = session.createCriteria(entityClazz)
.add( Subqueries.propertiesIn(new String[] { COMPOSEDID_VERSION_ID, COMPOSEDID_ID }, detachedCriteria));
This query worked fine with Postgre Db. But when i switch to MSSQL i get the following error:
Caused by: java.sql.SQLException: An expression of non-boolean type specified in a context where a condition is expected, near ','.
at net.sourceforge.jtds.jdbc.SQLDiagnostic.addDiagnostic(SQLDiagnostic.java:372)
at net.sourceforge.jtds.jdbc.TdsCore.tdsErrorToken(TdsCore.java:2988)
at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2421)
at net.sourceforge.jtds.jdbc.TdsCore.getMoreResults(TdsCore.java:671)
at net.sourceforge.jtds.jdbc.JtdsStatement.executeSQLQuery(JtdsStatement.java:505)
at net.sourceforge.jtds.jdbc.JtdsPreparedStatement.executeQuery(JtdsPreparedStatement.java:1029)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70)[201:org.hibernate.core:5.0.0.Final]
Can anyone help me out? What change should i made in Criteria API to achieve my goal to get maxVersion record against each Id??
Instead of adding subqueries in criteria of projections from detached critaria, add projection directly in critaria like this:
DetachedCriteria detachedCriteria=DetachedCriteria.forClass(entityClazz);
ProjectionList proj = Projections.projectionList();
proj.add(Projections.max(COMPOSEDID_VERSION_ID));
proj.add(Projections.groupProperty(COMPOSEDID_ID));
criteria = session.createCriteria(entityClazz)
.setProjection( proj );
I need to be able to execute an update SQL script, but it isn't working
Here is a link to the site that I used for reference:
https://groovyinsoapui.wordpress.com/tag/sql-eachrow-groovy-soapui/
Here is the format of the code that I ended up writing (due to the nature of the work I am doing, I am unable to provide the exact script that I wrote)
import groovy.sql.Sql
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
groovyUtils.registerJdbcDriver("com.microsoft.sqlserver.jdbc.SQLServerDriver")
def connectString = "jdbc:microsoft:sqlserver://:;databaseName=?user=&password="
sql = Sql.newInstance(connectString) // TEST YOUR CONNECT STRING IN A SQL BROWSER
sql.executeUpdate("UPDATE TABLE SET COLUMN_1 = 'VALUE_1' WHERE COLUMN_2 = 'VALUE_2'")
The response that I am getting is:
Script-result: 0
I also tried to use:
sql.execute("UPDATE TABLE SET COLUMN_1 = 'VALUE_1' WHERE COLUMN_2 = 'VALUE_2'")
Which returns the following response:
Script-result: false
From what you say it seems that no row has COLUMN_2 = 'VALUE_2', so then number of updated rows is 0.
I would first check that statement on Management Studio just to make sure.
Dapper 1.34 (on earlier Dapper ver like 1.1x this worked fine).
db.Query(#"Select [whatever] from #TableName Where [PREFIX]='#Prefix' order by [something] desc",
new { TableName = tableName, Prefix = prefix })
Error: System.Data.SqlClient.SqlException (0x80131904): Must declare the table variable "#TableName".
I get same error trying to define DynamicParameters and passing those.
=======
I am currently doing string substitution {%1} .. but that does not seem acceptable ...
Can I please get a sample, also looking at test class for dapper I cant see it running, maybe something wrong with my project setup ?
No, that has never worked fine, due to how SQL works:
table names cannot be parameterized, and dapper has never offered this; that could work if you pass in a DataTable as a table-valued-parameter, though - which dapper does support - but I don't think this is what you are after
'#Prefix' is a string literal; you just mean #Prefix (no single quotes)
I am using Hibernate to access my database. I would like to delete a set of fields on function of a criteria. My database is PostgreSQL and my Java code is:
public void deleteAttr(String parameter){
Configuration cfg = new Configuration();
cfg.configure(resource.getString("hibernate_config_file"));
SessionFactory sessionFactory = cfg.buildSessionFactory();
session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
tx.begin();
String sql = "delete from attribute where timestamp > to_date('"+parameter+"','YYYY-MM-DD')"
session.createSQLQuery(sql);
tx.commit();
}
The method runs, but it doesn't delete data from database. I have also checked the sql sentence in PgAdmin and it works, but not in code. Why? Does someone help me?
Thanks in advance!
It's because you're creating a query, but you don't execute it:
String sql = "delete from attribute where timestamp > to_date('"+parameter+"','YYYY-MM-DD')"
Query query = session.createSQLQuery(sql);
query.executeUpdate();
You should really use bound named parameters rather than string concatenation to pass parameters in your query: it's usually more efficient, it' much more robust, but above all, it doesn't open the door to SQL injection attacks.