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!!
Related
I am using Spring with hibernate (and JDK 17)
I have the following Query that calculates the distance in meters between 2 points:
SELECT v.VehicleId,
(geography::Point(4.40333979390196, 51.1743639872608, 4326)).STDistance(geography::Point(v.Point.STY, v.Point.STX, 4326)) distance
FROM (SELECT * FROM Vehicles) v
ORDER BY distance;
The first point is currently hardcoded since they are passed as parameters.
The query might also look a bit confusing but since my database type is 'geometry' instead of 'geography' I have to convert it first.
This query run perfectly fine in sqlserver.
The problem is I have to make it work in spring, and thus I created my own custom repository:
public class VehicleRepository {
#PersistenceContext
private EntityManager entityManager;
public void findClosestVehicle(double longitude, double latitude) {
var queryString = "SELECT v.VehicleId," +
" (geography::Point("+latitude+", "+longitude+", 4326)).STDistance(geography::Point(v.Point.STY, v.Point.STX, 4326)) distance" +
"FROM (SELECT * FROM Vehicles) v " +
"ORDER BY distance;";
Query query = entityManager.createNativeQuery(queryString);
}
}
As you can see I haven't even run the query yet, but Intellij says there are errors in the SQL syntax. It doesn't recognize:
v, distance
::
.STDistance
Is there any way I can suppress this since I know the SQL is correct because it runs fine in'Microsoft SQL Server Management Studio)?
I am tried to use .FromSqlRaw and .FromSqlInterpolated in ASP.NET Core 3.1, EntityFramework Core 3.1, DotVVM, SQL Server.
var result = SomeDbContext
.SomeModels
.FromSqlRaw("Select [column1], [column2] From [schema].[ufnTableValueFunction] (#FirstParam, #SecondParam, #ThirdParam)",
parameters: new[] { firstParam, secondParam, thirdParam })
.AsNoTracking()
.ToListAsync();
var result = SomeDbContext
.SomeModels
.FromSqlInterpolated($"select * from [schema].[ufnTableValueFunction] ({firstParam},{secondParam},{thirdParam})")
.AsNoTracking()
.ToListAsync();
When I use SQL Server Profiler, I find this generated SQL from application and I try use it in database, it is returned data to me. In application no data returned into result. In second application with same system of selecting data with table-valued function all is working fine. What I must do for successful selecting data?
I've included Microsoft.SqlServer.Types to enable the geography and geometry types in Entity Framework, but I don't see any functions equivalent to STContains().
I need to make a query to retrieve the geography that contains a point
In SQL I wrote like this:
SELECT adm1code, adm1name
FROM Adm2GeoBoundaries
WHERE Coords.STContains(geography::Parse('POINT(-121.703796 46.893985)'));
in LINQ I expect to have something like
using (GeoEntities db = new GeoEntities ())
{
DbGeography location = DbGeography.FromText("POINT(-121.703796 46.893985)");
var admin = from a in db.Adm2GeoBoundaries
where a.Coords.STContains(location)
select a;
}
but a.Coords.STContains(location) throws an error
STContains method doesn't exist
According to the source code for EF6 Source Code, the STContains seems to be implemented as Contains in EF6.
https://github.com/aspnet/EntityFramework6/blob/master/src/EntityFramework.SqlServer/SqlSpatialServices.cs
Looking at the SqlTypesAssembly.cs you should be able see it should invoke the STContains method.
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.
In my application I need to get database date(sysdate in case of Oracle DB) and compare it with user input date (String converted to java.util.Date). From this forum I got the following code which helps in the case of Oracle dialect.
public Date getDate() {
Session session = getHibernateTemplate().getSessionFactory().openSession();
SQLQuery query = session.createSQLQuery("select sysdate as mydate from dual");
query.addScalar("mydate", Hibernate.TIMESTAMP);
return (Date) query.uniqueResult();
}
And from this link got the following method which uses mapping file with formula.
<property name="currentDate" formula="(select sysdate from dual)"/>
Again this is specific to Oracle. I think using later method is more performance friendly, because we can get it from the same session, i.e no need of opening another session just for getting date.
I am looking for a generic solution to get date, time and timestamp from any DBMS using Hibernate. Using HQL is the preferred. Hope such a solution is available.
For those who are looking for .NET /C# solution, here is what worked for me:
// this works only with Oracle
public DateTime DbTimeStamp(ISession session)
{
// Sample returned value = "12-OCT-11 01.05.54.365134000 AM -07:00"
string sql = "SELECT SYSTIMESTAMP FROM DUAL";
ISQLQuery query = session.CreateSQLQuery(sql)
.AddScalar("SYSTIMESTAMP", NHibernate.NHibernateUtil.DateTime);
return query.UniqueResult<DateTime>();
}