Why jpa binding enum parameter as varbinary - spring-data-jpa

Why jpa binding enum parameter as varbinary?
#Query(value = "select * from person where skin in :skin",nativeQuery=true)
List<People> findInSkins(Skin[] skin);
Here is the log
Hibernate: select * from person where skin in (?, ?)
2019-11-12 18:59:57.282 TRACE 141600 --- [nio-8081-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARBINARY] - [Yellow]
2019-11-12 18:59:57.283 TRACE 141600 --- [nio-8081-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [VARBINARY] - [Black]

If you want jpa to bind it as a String you should use this decorator:
**#Enumerated(EnumType.STRING)**

Related

Hibernate not updating schema automatically

I am using SpringBoot with Hibernate. I have 2 Postgres datasources. I have an existing database (pims) and a new database (powwow), and some entities. When I start up SpringBoot, I would like it to automatically create the tables in the new powwow database, however it is not doing so.
application.properties
# pims datasource
spring.datasource1.driver-class-name=org.postgresql.Driver
spring.datasource1.jdbc-url=jdbc:postgresql://localhost:5432/pims
spring.datasource1.username=postgres
spring.datasource1.password=postgres
# powwow datasource
spring.datasource2.driver-class-name=org.postgresql.Driver
spring.datasource2.jdbc-url=jdbc:postgresql://localhost:5432/powwow
spring.datasource2.username=postgres
spring.datasource2.password=postgres
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.database-platform=postgres
spring.jpa.hibernate.ddl-auto=update
#spring.jpa.properties.hibernate.hbm2ddl.auto=update
#spring.jpa.generate-ddl=true
#spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.datasource2.dbcp2.test-while-idle=true
spring.datasource2.dbcp2.validation-query=select 1
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl
spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
# logging
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
Example entity:
PowWowActivityEntity.java
#Entity
#Table(name = "powwowactivity")
public class PowWowActivityEntity {
#Id
#Column(name = "activity_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long activity_id;
#Column(name = "status")
private String status;
Output
2022-08-16 09:19:13.227 INFO 65945 --- [ main] com.clubtravel.powwow.PowWowApplication : Started PowWowApplication in 11.544 seconds (JVM running for 12.617)
2022-08-16 09:19:13.255 DEBUG 65945 --- [ scheduling-1] org.hibernate.SQL : select count(*) as col_0_0_ from powwowglaccountmapping powwowglac0_
2022-08-16 09:19:13.269 DEBUG 65945 --- [ Async-1] org.hibernate.SQL : insert into powwowactivity (comment, create_date, status, user_name) values (?, ?, ?, ?)
2022-08-16 09:19:13.272 TRACE 65945 --- [ Async-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [Server started on HOST: Richards-MacBook-Pro.local.]
2022-08-16 09:19:13.273 TRACE 65945 --- [ Async-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [TIMESTAMP] - [Tue Aug 16 09:19:13 SAST 2022]
2022-08-16 09:19:13.274 TRACE 65945 --- [ Async-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [3] as [VARCHAR] - [Info]
2022-08-16 09:19:13.274 TRACE 65945 --- [ Async-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [4] as [VARCHAR] - [system]
2022-08-16 09:19:13.281 WARN 65945 --- [ Async-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 42P01
2022-08-16 09:19:13.281 ERROR 65945 --- [ Async-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: relation "powwowactivity" does not exist
Question
I thought by adding the following line, the new tables would automatically be created by updating the schema. Any ideas? Is this not working because I have more than one datasource?
spring.jpa.hibernate.ddl-auto=update
The reason it was not working is because i have 2 datasources defined. If i change the config to update, it works (properties.put("hibernate.hbm2ddl.auto", "update");):
#Bean(name = "powwowEntityManager")
#Primary
public LocalContainerEntityManagerFactoryBean powwowEntityManager() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(powwowDataSource());
em.setPackagesToScan(new String[] { "com.clubtravel.powwow.entities.powwow" });
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<>();
// properties.put("hibernate.hbm2ddl.auto",env.getProperty("hibernate.hbm2ddl.auto"));
// properties.put("hibernate.dialect",env.getProperty("hibernate.dialect"));
properties.put("hibernate.hbm2ddl.auto", "update");
properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
em.setJpaPropertyMap(properties);
logger.info("Setting spring.datasource2 (powwowEntityManager) hibernate.hbm2ddl.auto = "+env.getProperty("hibernate.hbm2ddl.auto")+" and hibernate.dialect = "+env.getProperty("hibernate.dialect"));
return em;
}

Query Native - could not extract ResultSet

i have a problem.I explain my situation: SpringBoot + Hibernate + Multitenant (DB master + DB for tenant) + Postgressql. I have two datasource configurations, one for the master and one for each client's database. I need doing a query native in JPARepository And that's the only way I can do it
In my JPARepository :
public interface IEntity extends JpaRepository<Entity, Integer> {
........
#Query(value = "ALTER SEQUENCE entity_identity_seq RESTART", nativeQuery = true)
#Modifying ///Add 1
#Transactional ///Add 2
void restarID();
}
when I first call the method, I got:
> Hibernate:
ALTER SEQUENCE entity_identity_seq RESTART
> 2019-09-10 15:41:53.919 WARN 18680 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 02000
> 2019-09-10 15:41:53.919 ERROR 18680 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : La consulta no retornó ningún resultado.
> 2019-09-10 15:41:53.940 ERROR 18680 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet] with root cause
org.postgresql.util.PSQLException: La consulta no retornó ningún resultado.
After looking for solutions and discovered that he needed to add
#Query(value = "ALTER SEQUENCE entity_identity_seq RESTART", nativeQuery = true)
#Modifying
void restarID();
But the query is not made in hibernate and this error comes up:
> 2019-09-10 15:46:57.972 ERROR 14392 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query] with root cause
javax.persistence.TransactionRequiredException: Executing an update/delete query
I keep searching and find that I should add #Transactional. Then :
#Query(value = "ALTER SEQUENCE entity_identity_seq RESTART", nativeQuery = true)
#Modifying
#Transactional
void restarID();
But, then come back, I call the method, I got:
> Hibernate:
ALTER SEQUENCE entity_identity_seq RESTART
> 2019-09-10 15:41:53.919 WARN 18680 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 02000
> 2019-09-10 15:41:53.919 ERROR 18680 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : La consulta no retornó ningún resultado.
> 2019-09-10 15:41:53.940 ERROR 18680 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet] with root cause
org.postgresql.util.PSQLException: La consulta no retornó ningún resultado.
Please, will anyone have any recommendations?
I am new to hibernate. Thank you.
If someone yet have the same problem, I've resolved it, adding the next to the query:
#Modifying(clearAutomatically = true)
#Transactional

How to pass argument to JPA when using Postgres LTREE?

I have a Spring Boot app that is using JPA and a Postgres table with ltree data structure.
It works when I query using sql statement but not when I pass an argument.
Controller
#GetMapping("/path")
ResponseEntity<?> findAllByPath() {
List<Tree> allByPath = treeRepository.findAllByPath("A");
return ResponseEntity.ok().body(allByPath);
}
Working Code in Repository
#Query(value = "SELECT * FROM Tree WHERE path <# 'A'", nativeQuery = true)
List<Tree> findAllByPath(#Param("pathToSearch") String pathToSearch);
*Not Working Code in Repository
#Query(value = "SELECT * FROM Tree WHERE path <# '" + ":pathToSearch" +"'", nativeQuery = true)
List<Tree> findAllByPath(#Param("pathToSearch") String pathToSearch);
Error
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Jan 04 17:41:43 CET 2019
There was an unexpected error (type=Internal Server Error, status=500). could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Stacktrace
2019-01-04 17:41:43.357 DEBUG 33826 --- [nio-8080-exec-1] org.hibernate.SQL :
SELECT
*
FROM
Tree
WHERE
path <# ':pathToSearch'
Hibernate:
SELECT
*
FROM
Tree
WHERE
path <# ':pathToSearch'
2019-01-04 17:41:43.362 WARN 33826 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 42601
2019-01-04 17:41:43.363 ERROR 33826 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: syntax error at position 0
Position: 34
2019-01-04 17:41:43.381 ERROR 33826 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
org.postgresql.util.PSQLException: ERROR: syntax error at position 0
Position: 34
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440) ~[postgresql-42.2.5.jar:42.2.5]
EDIT:
When I try removing the quotes in the Query, it fails with another error.
#Query(value = "SELECT * FROM Tree WHERE path <# :pathToSearch", nativeQuery = true)
List<Tree> findAllByPath(#Param("pathToSearch") String pathToSearch);
2019-01-08 12:52:25.213 DEBUG 18840 --- [nio-8080-exec-1] org.hibernate.SQL :
SELECT
*
FROM
Tree
WHERE
path <# ?
Hibernate:
SELECT
*
FROM
Tree
WHERE
path <# ?
2019-01-08 12:52:25.222 TRACE 18840 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [A]
2019-01-08 12:52:25.240 WARN 18840 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 42883
2019-01-08 12:52:25.240 ERROR 18840 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: operator does not exist: ltree <# character varying
Hint: No operator matches the given name and argument types. You might need to add explicit type casts.
Position: 31
2019-01-08 12:52:25.266 ERROR 18840 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
org.postgresql.util.PSQLException: ERROR: operator does not exist: ltree <# character varying
Hint: No operator matches the given name and argument types. You might need to add explicit type casts.
Position: 31
I fixed it by casting the parameter to ltree.
The modified method and query in the Repository is:
#Query(value = "SELECT * FROM Tree WHERE path <# CAST(:pathToSearch AS ltree)", nativeQuery = true)
List<Tree> findAllByPath(#Param("pathToSearch") String pathToSearch);

Spring data #Query joda datetime postgresql exception

I have an Entity with 2 Columns with joda DateTime.
#Column(name = "track_start", columnDefinition= "TIMESTAMP WITH TIME ZONE")
#Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime start;
#Column(name = "tracke_end", columnDefinition= "TIMESTAMP WITH TIME ZONE")
#Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime end;
Then I have a Spring data Repository with a find method:
#Query("SELECT tt FROM Timetrack tt "
+ "WHERE (:dateFrom is null OR tt.start >= :dateFrom) "
+ "AND (:dateTo is null OR tt.end <= :dateTo)")
Page<Timetrack> findBy(#Param("dateFrom") DateTime dateFrom,
#Param("dateTo") DateTime dateTo,
Pageable pageable);
If I call that finder method I got an Exception:
org.postgresql.util.PSQLException: ERROR: could not determine data type of parameter $2
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2455)
If I change the #Param to Date instead of DateTime I got this Exception:
java.lang.IllegalArgumentException: Parameter value [Fri Jun 01 19:26:44 CEST 2018] did not match expected type [org.joda.time.DateTime (n/a)]
at org.hibernate.jpa.spi.BaseQueryImpl.validateBinding(BaseQueryImpl.java:897)
at org.hibernate.jpa.internal.QueryImpl.access$000(QueryImpl.java:61)
So does somebody have an idea?
Here the logging output from hibernate:
Hibernate: select timetrack0_.id as id1_6_, timetrack0_.created as created2_6_, timetrack0_.entity_status as entity_s3_6_, timetrack0_.updated as updated4_6_, timetrack0_.user_identity_id as user_ide9_6_, timetrack0_.tracke_end as tracke_e5_6_, timetrack0_.frozen_at as frozen_a6_6_, timetrack0_.invoice_id as invoice10_6_, timetrack0_.project_id as project11_6_, timetrack0_.track_start as track_st7_6_, timetrack0_.task as task8_6_ from timetrack timetrack0_ where ( timetrack0_.entity_status = 'active') and (? is null or timetrack0_.track_start>=?) and (? is null or timetrack0_.tracke_end<=?) order by timetrack0_.track_start asc limit ? offset ?
2018-06-09 21:32:05.804 TRACE 14006 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [TIMESTAMP] - [2018-06-09 20:32:05.604]
2018-06-09 21:32:05.806 TRACE 14006 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [TIMESTAMP] - [2018-06-09 20:32:05.604]
2018-06-09 21:32:05.808 TRACE 14006 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [3] as [TIMESTAMP] - [2018-06-10 02:32:05.604]
2018-06-09 21:32:05.809 TRACE 14006 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [4] as [TIMESTAMP] - [2018-06-10 02:32:05.604]

Criteria query cache caching in Eclipselink?

Iam using criteria queries with EclipseLink as JPA . I need to cache the query results based on their parameters . When I used query.setHint("eclipselink.QUERY_RESULTS_CACHE", "TRUE") it still fires query to the database. How can I use it in context of criteria queries ?
Here I set my query and their hints and addNamedQuery
Query query = psEntityManager.getEntityManager().createQuery(criteriaQuery);// Creating Query to supply Values
query.setHint("eclipselink.QUERY_RESULTS_CACHE", "TRUE");
query.setHint(QueryHints.QUERY_TYPE,QueryType.ReadObject);
psEntityManager.getEntityManager().getEntityManagerFactory().addNamedQuery("query1", query);
Here is my output :
Query1-----------
[EL Fine]: sql: 2013-10-10 21:33:35.495--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, ADDRESSLINE1, ADDRESSLINE2, PHONENUMBER, fkCityId, fkPersonId FROM ADDRESS WHERE (fkPersonId = ?)
bind => [2]
[EL Fine]: sql: 2013-10-10 21:33:35.527--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, CITYNAME, PINCODE, fkStateId FROM CITY WHERE (PRIMARYKEY = ?)
bind => [2]
[EL Fine]: sql: 2013-10-10 21:33:35.528--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, STATENAME FROM STATE WHERE (PRIMARYKEY = ?)
bind => [1]
[EL Fine]: sql: 2013-10-10 21:33:35.531--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, AGE, DOB, FIRSTNAME, LASTNAME, SEX, TIMESTAMP, fkDepartmentId FROM PERSON WHERE (PRIMARYKEY = ?)
bind => [2]
[EL Fine]: sql: 2013-10-10 21:33:35.541--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, DEPTNAME FROM DEPARTMENT WHERE (PRIMARYKEY = ?)
bind => [2]
[EL Fine]: sql: 2013-10-10 21:33:35.547--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, CITYNAME, PINCODE, fkStateId FROM CITY WHERE (PRIMARYKEY = ?)
bind => [5]
[EL Fine]: sql: 2013-10-10 21:33:35.548--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, STATENAME FROM STATE WHERE (PRIMARYKEY = ?)
bind => [3]
[EL Fine]: sql: 2013-10-10 21:33:35.551--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, CITYNAME, PINCODE, fkStateId FROM CITY WHERE (PRIMARYKEY = ?)
bind => [8]
[EL Fine]: sql: 2013-10-10 21:33:35.553--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, STATENAME FROM STATE WHERE (PRIMARYKEY = ?)
bind => [4]
Query2-----------
[EL Fine]: sql: 2013-10-10 21:33:35.557--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, ADDRESSLINE1, ADDRESSLINE2, PHONENUMBER, fkCityId, fkPersonId FROM ADDRESS WHERE (fkPersonId = ?)
bind => [2]
Query3-----------
[EL Fine]: sql: 2013-10-10 21:33:35.56--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, ADDRESSLINE1, ADDRESSLINE2, PHONENUMBER, fkCityId, fkPersonId FROM ADDRESS WHERE (fkPersonId = ?)
bind => [2]
Query4-----------
[EL Fine]: sql: 2013-10-10 21:33:35.563--ServerSession(14144548)--Connection(7200601)--SELECT PRIMARYKEY, ADDRESSLINE1, ADDRESSLINE2, PHONENUMBER, fkCityId, fkPersonId FROM ADDRESS WHERE (fkPersonId = ?)
bind => [2]
Remove the query.setHint(QueryHints.QUERY_TYPE,QueryType.ReadObject), or call it first. The query_type changes the underlying query object, and not all the hints might be copied into the new object. It seems unnecessary anyway.