The project that I'm working on has the following setup: JPA 2.0 (Hibernate 4 implementation) and SQL Server 2008 R2.
I need to select some data from an SQL view. In order to do this I use a native query, but I ran into some problems with the NVARCHAR fields. Basically, when using this piece of code:
String sql = "SELECT v.text_field as address FROM SOME_CUSTOM_VIEW v
Query q = entityManager.createNativeQuery(sql,"ItemDetailsMapping");
List<Object[]> result = q.getResultList();
The ItemDetailsMapping is declared like:
#SqlResultSetMapping(name = "ItemDetailsMapping", columns = { #ColumnResult(name = "address") })
I get an exception saying:
org.springframework.orm.hibernate3.HibernateSystemException: No Dialect mapping for JDBC type: -9; nested exception is org.hibernate.MappingException: No Dialect mapping for JDBC type: -9
Type -9 is actually the NVARCHAR type, which we are extensively using throughout the application and it works perfectly when we are using non-native queries. Why is it not working with native queries? I even used a custom dialect and registered the type, but it's still not working.
Thanks a lot for your help
You have to associate the data type NVARCHAR to String.When using Hibernate via Session interface, you can explcitly set a type of result with addScalar() instead (also accessible via unwrap() in JPA 2.0):
So modify your code as below,
String sql = "SELECT v.text_field as address FROM SOME_CUSTOM_VIEW v"
Query q = entityManager.createNativeQuery(sql,"ItemDetailsMapping");
q.unwrap(SQLQuery.class).addScalar("address ", StringType.INSTANCE);
List<Object[]> result = q.getResultList();
Read here for more information.
(Edit 7/1/15 -- Added quotation mark for clarity)
You can do it like this:
String myquery = "select cast(t2.name as varchar) column_name from sys.objects t1 inner join sys.columns t2 on t2.object_id = t1.object_id"+
" left join sys.indexes t3 on t3.object_id = t1.object_id and t3.is_unique = 1 left join sys.index_columns t4 on t4.object_id = t1.object_id and t4.index_id = t3.index_id and t4.column_id = t2.column_id where (upper(t1.type) = 'U' or upper(t1.type) = 'V') and upper(schema_name(t1.schema_id)) = 'dbo' and upper(t1.name) = 'TEST'";
Related
JPA repository throwing Error for custom query method:
org.h2.jdbc.JdbcSQLException: Table "NBMRBANKDTLSENTITY" not found; SQL statement:
select NBMRBankDtlsEntity from NBMRBankDtlsEntity where NBMRBankDtlsEntity.ipphId = ? [42102-191]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
Class :
#Repository
public interface NBMRBankDtlsRepository extends JpaRepository<NBMRBankDtlsEntity, Long> {
#Query(value ="select n from NBMRBankDtlsEntity n where n.ipphId = :ipphId",nativeQuery = true)
Optional<NBMRBankDtlsEntity> findByIPPHId(#Param("ipphId") Long ipphId);
}
The error message tells you: Table "NBMRBANKDTLSENTITY" not found. Therefore it probably doesn't exist. To fix this you'll have to create the table, manually through a script or through hibernates schema creation feature.
I am already creating a table also inserting the record, After that only i am calling this custom query method.
I have found the issue as i am using nativeQuery = true so it is expecting normal sql query to query DB directly not the java query which is creating issue. Now after changing below it works fine ,
#Query(value = "SELECT * from NB_MR_BANK_DTLS WHERE IPPH_ID = :ipphId",nativeQuery = true)
For java query we can use directly as it internally converts to SQL while querying the DB,
#Query(value = "select p from NBMRBankDtlsEntity p WHERE p.ipphId = :ipphId")
I am using the below #Query annotation to get the first few record from MS-SQL. It's showing error saying "< operator > or AS expected..."
#Query("SELECT Top 1 * FROM NEVS010_VEH_ACTV_COMMAND C WHERE C.EVS014_VIN = :vin ORDER BY C.EVS010_CREATE_S DESC")
CommandStatus findCommandStatusByVinOrderByCreatedTimestampDesc(#Param("vin") String vin);
You can also use findFirst and findTop as mentioned in the Docs:
findFirstByVinOrderByCreatedTimestampDesc(String vin)
Since the query is SQL (and not JPQL) one needs to set nativeQuery = true in the annotation:
#Query(nativeQuery = true, value = "SELECT Top 1 * FROM NEVS010_VEH_ACTV_COMMAND C WHERE C.EVS014_VIN = :vin ORDER BY C.EVS010_CREATE_S DESC")
CommandStatus findCommandStatusByVinOrderByCreatedTimestampDesc(#Param("vin") String vin);
For custom Queries without using nativeQuery, the field ROWNUM can be used.
Ex (in Kotlin but the same idea works in Java):
#Query("""
SELECT a
FROM Account a
WHERE a.bla = :ble
AND ROWNUM = 1
ORDER BY a.modifiedDate DESC
""")
fun findWhatever(#Param("ble") someParam: String)
I haven't found that on any doc so far. I just tested and it worked for Oracle, MySQL and H2
Am trying to perform a query with LIKE expression on a date field using a named query as shown below ;
public Users getResultsByDate(Date regDate){
List<Users> dbUsers = new ArrayList<Users>();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Query searchQuery = getEntityManager().createNamedQuery("getUserByRegDate");
searchQuery.setParameter("regDate", "%"+dateFormat.format(regDate)+"%");
try{
dbUsers = searchQuery.getResultList();
}
catch(Exception ex){
dbUsers = new ArrayList<Users>();
}
return dbUsers;
}
The name query in corresponding class is;
#NamedQuery(name = "getUserByRegDate", query = "SELECT user FROM Users user WHERE user.regDate LIKE :regDate"),
The query was working using previous JPA 2.0 version. I get the following error when i execute the same when running on JPA 2.1;
You have attempted to set a value of type class java.lang.String for
parameter :regDate with expected type of class java.util.Date ...
How can i resolve this when running on JPA 2.1 ? It's Working OK in JPA 2.0.
JPA spec 4.6.10
The syntax for the use of the comparison operator [NOT] LIKE in a
conditional expression is as follows:
like_expression ::=
string_expression [NOT] LIKE pattern_value [ESCAPE escape_character]
The string_expression must have a string value. The pattern_value is a
string literal or a string-valued input parameter ...
So no, it does not "work" in JPA 2.0; it is not part of ANY JPA spec to use Date in LIKE expressions. It may have just worked by accident because some JPA provider (which one?) didn't do a check and enforce the JPA spec ...
Try with a native named query, transforming user.reg_date to string and then comparing it with the operator like to the parameter. In case of an Oracle DB it would be for example:
#NamedNativeQuery(name = "getUserByRegDate", query =
"SELECT user FROM Users user WHERE TO_CHAR(user.reg_date, 'DD-MON-YYYY') LIKE :regDate"),
Key is to use DB functions 'TO_CHAR' (ORACLE) or MySQL function 'date_format' then user FUNCTION IN #NamedQuery as shown below ;
ORACLE DB
#NamedQuery(name = "getUserByRegDate", query = "SELECT user FROM Users user WHERE FUNCTION('TO_CHAR',user.reg_date,'yyyy-MM-dd') LIKE :regDate")
MySQL
Change 'TO_CHAR' above to 'date_format'
#NamedQuery(name = "getUserByRegDate", query = "SELECT user FROM Users user WHERE FUNCTION('date_format',user.reg_date,'%Y-%m-%d') LIKE :regDate")
Also see http://www.w3schools.com/sql/func_date_format.asp for more info on the DATE_FORMAT MySQL Function.
Thanks.
I tried to run native sql query with resulttransformer (AliasToBeanResultTransformer), it gives error like below.
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: com.ozpas.ozentegre.entity.EntDevirlog cannot be cast to java.util.Map
at org.hibernate.property.access.internal.PropertyAccessMapImpl$SetterImpl.set(PropertyAccessMapImpl.java:102)
at org.hibernate.transform.AliasToBeanResultTransformer.transformTuple(AliasToBeanResultTransformer.java:78)
By the way, my native sql query does not include all fields in the entity ( EntDevirlog ), there are only some fields in that entity. shall the query include all fields in the entity ?
as i understood, hibernate transforms result into a map object instead EntDevirlog entity. It uses PropertyAccessMapImpl. how can i solve this problem to get the result as a list ( arraylist ) ? thanks.
Session session = HibernateUtilMikro.getSessionFactory().openSession();
List<EntDevirlog> results = new ArrayList<EntDevirlog>();
Transaction tx = null;
String sql = "mynativequery";
SQLQuery query = session.createSQLQuery(sql);
query.setParameter("tarih", tarih);
query.setParameter("srmkodu", srmkodu);
query.setParameter("s1", EnumPanoislemtipleri.islem1.getValue());
query.setParameter("s2", EnumPanoislemtipleri.islem2.getValue());
query.setResultTransformer(new AliasToBeanResultTransformer(EntDevirlog.class));
results = query.list();
tx.commit();
Just use the quotes for the aliases
"select firstName as \"firstName\",
lastName as \"lastName\" from Employee"
Read for a more deeply explanation here:
mapping Hibernate query results to custom class?
My entity has a named query which looks like this:
#NamedQuery(name = "Person.find", query = "select p from Organization p where p.name=:NAME")
In my code I want to set the query cache hint:
query.setHint("eclipselink.cache-usage", "CheckCacheThenDatabase");
If I try to get whole result list:
List<Person> result = query.getResultList();
EclipseLink throws an exception:
Exception [EclipseLink-6124] (Eclipse Persistence Services - 1.0.1 (Build 20080905)): org.eclipse.persistence.exceptions.QueryException
Exception Description: Required query of class org.eclipse.persistence.queries.ReadAllQuery, found class org.eclipse.persistence.queries.ReadObjectQuery
If I try to get only a single result, it works:
Person person = query.getSingleResult();
If I remove the query hint, then getResultList() works also.
I don't understand the exception - isn't it saying that it is specifically expecting getResultList()?? What am I doing wrong?
EclipseLink documentation says:
"EclipseLink does not support the cache usage for native queries or queries that have complex result sets such as returning data or multiple objects."
Also the documentation says:
"CheckCacheThenDatabase – You can configure any read-object query to check the cache completely before you resort to accessing the database."
So the behaviour seems to be ok, I just found the exception misleading.
EDIT: Try something like this in the entity definition, that should be enough: (Coded on the web page so there can be errors)
Entity
#Cache(expiry = 3600000, // 1 hour size = 10000)
#NamedQueries({
#NamedQuery(name = "Person.findByPK", query = "select p from Person p " +
"where p.name=:NAME",
hints = {
#QueryHint(name = QueryHints.CACHE_USAGE,
value = CacheUsage.CheckCacheThenDatabase),
#QueryHint(name = QueryHints.QUERY_TYPE, value = QueryType.ReadObject)
}
})