Spring Boot Application - H2 Database (1.4.200) Array column, Hibernate mapping - spring-boot

I'm creating a Spring Boot application, where I have a Routes table. Within the Routes table I have stops column where I want to store the integer array of stop id.
Since H2 database (version 1.4.200) doesn't support typed array, I defined it as generic array.
CREATE TABLE Routes (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(250) NOT NULL,
stops ARRAY[100] NOT NULL
);
INSERT INTO Routes (id, name, stops) VALUES (1, '500CK', (1,2));
SELECT * FROM Routes;
ID NAME STOPS
1 500CK [1, 2]
I want to know what should be the type of stops property (any other configuration required) so it works with Hibernate
#Entity
#Table(name = "Routes")
public class Route {
#Id
#GeneratedValue
private int id;
private String name;
// I'm not sure what should be the data type of stops
private Object[] stops;
}
I'm getting below error while trying to get the route from /route endpoint
org.h2.jdbc.JdbcSQLDataException: Hexadecimal string contains non-hex character: "[1, 2]" [90004-200]
I created the Routes table by defining the DDL in the schema.sql file
DROP TABLE IF EXISTS Routes;
CREATE TABLE Routes (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(250) NOT NULL,
stops ARRAY[100] NOT NULL
);
And I inserted one record by defining the DML in data.sql file
INSERT INTO ROUTES (id, name, stops) VALUES
(1, '500CK', (1,2));
UPDATE :
I updated h2 to 2.1.212
CREATE TABLE Routes (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(250) NOT NULL,
stops INTEGER ARRAY[100] NOT NULL
);
INSERT INTO ROUTES (id, name, stops) VALUES(1, '500CK', ARRAY[1, 2]);
I can see the above record in the Routes table.
Changed the Route entity as below
#Entity
#Table(name = "Routes")
public class Route {
#Id
#GeneratedValue
private int id;
private String name;
private Integer[] stops;
// getter & setters
}
I'm getting below error
org.h2.jdbc.JdbcSQLDataException: Data conversion error converting "ARRAY to BINARY VARYING" [22018-212]
I'm using hibernate-core 5.6.8.Final
Looks like Hibernate is not able to do the conversion.
Can I achieve it with just Hibernate, Or do I have to do it, the way mentioned here
https://vladmihalcea.com/how-to-map-java-and-sql-arrays-with-jpa-and-hibernate/
Update : Trying to update hibernate-core to 6.1.0.Final
I tried to update the hibernate-core to 6.1.0.Final.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.1.0.Final</version>
</dependency>
But I'm getting below error
Field routeRepository in net.mahtabalam.service.RouteService required a bean named 'entityManagerFactory' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean named 'entityManagerFactory' in your configuration.
Looks like this is caused due to dependency version conflicts.
Below is the project pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>net.mahtabalam</groupId>
<artifactId>routes</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>routes</name>
<description>Bus Routes</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.1.212</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

Unfortunately to my knowledge there will be no way to use hibernate 6.1.0.Final with Spring Boot currently. The issue you've noted with entityManagerFactory will be because the hibernate-entitymanager project was moved into hibernate-core in version 6.1.0.Final.
Looking through the plans for Spring Boot, see here, it looks like there is no imminment plan to update the version of hibernate used either as it won't be until M3 of version 3.
Instead your best bet will be to make a custom converter, I am currently trying to tackle the exact same problem and if I find a solution I will share it.

Related

How to use Spring's BackendIdConverter?

I have an entity named VendorProductMapping with embedded primary key. Hence I want to use BackendIdConverter to convert the embedded primary key to string and vice-versa.
I followed a few posts on stackoverflow and learnt that I need to use BackendIdConverter.
I created the following class:
public class VendorProductMappingIdConverter implements BackendIdConverter {
#Override
public Serializable fromRequestId(String id, Class<?> entityType) {
--
}
#Override
public String toRequestId(Serializable source, Class<?> entityType) {
--
}
#Override
public boolean supports(Class<?> type) {
--
}
}
The very first line gives me an error saying
Cannot resolve symbol 'BackendIdConverter'
Do I explicitly need to create a BackendIdConverter interface ?
Here is my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>UI</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>UI</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-validation</artifactId>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
EDIT:
Now that I've written a converter class, how do I use this ?
I need to send the primary key of VendorProductMapping class (i.e, VendorProductMappingPk) may be in an anchor tag. The error I see is
Failed to convert value of type 'java.lang.String' to required type 'com.example.UI.entity.VendorProductMappingPk'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.example.UI.entity.VendorProductMappingPk': no matching editors or conversion strategy found
BackendIdConverter is part of Spring Boot Data REST, so try adding the following dependency. However, I am not sure this is what you need for your case.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
I would say you need a JPA converter to achieve this:
#Converter
public class PersonNameConverter implements AttributeConverter<YourEmbeddedPrimaryKeyClass, String> {
#Override
public String convertToDatabaseColumn(YourEmbeddedPrimaryKeyClass id) {
// your conversion to String logic
}
#Override
public YourEmbeddedPrimaryKeyClass convertToEntityAttribute(String id) {
// your conversion to YourEmbeddedPrimaryKeyClass logic
}
}
Then you can configure this converter in your model:
#Entity
#IdClass(PK.class)
public class YourClass {
#Id
private YourEmbeddedPrimaryKeyClass id;
...
}
public class PK implements Serializable {
#Column(name = "MY_ID_FIELD")
#Convert(converter = IdConverter.class)
private YourEmbeddedPrimaryKeyClass id;
}
You can check additional details at https://www.baeldung.com/jpa-attribute-converters.

Spring R2DBC - Getting "Table already exists" error while creating h2 table using schema.sql and ConnectionFactoryInitializer

Getting the error "Table Customer already exists" when i tried to create a table in H2 in memory database using schema.sql. I am using spring boot version: 2.5.4 and below is my pom.xml. It works fine if i use spring boot version: 2.4.3
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.sample</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-r2dbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-h2</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Here is my code:
#Data
#NoArgsConstructor
#AllArgsConstructor
public class Customer {
#Id
String id;
String name;
}
//schema.sql
CREATE TABLE CUSTOMER (id SERIAL PRIMARY KEY, name VARCHAR(255));
#SpringBootApplication
public class ReactivedemoApplication {
public static void main(String[] args) {
SpringApplication.run(ReactivedemoApplication.class, args);
}
#Bean
ConnectionFactoryInitializer initializer(ConnectionFactory connectionFactory) {
ConnectionFactoryInitializer initializer = new ConnectionFactoryInitializer();
initializer.setConnectionFactory(connectionFactory);
initializer.setDatabasePopulator(new ResourceDatabasePopulator(new
ClassPathResource("schema.sql")));
return initializer;
}
}
When i start the app, i am getting the below error. How to force H2 to create the table using schema.sql ?
Caused by: io.r2dbc.spi.R2dbcBadGrammarException: Table "CUSTOMER" already exists; SQL
statement:
CREATE TABLE CUSTOMER (id SERIAL PRIMARY KEY, name VARCHAR(255)) [42101-200]
at io.r2dbc.h2.H2DatabaseExceptionFactory.convert(H2DatabaseExceptionFactory.java:81) ~[r2dbc-h2-0.8.4.RELEASE.jar:0.8.4.RELEASE]
at io.r2dbc.h2.H2Statement.lambda$execute$2(H2Statement.java:155) ~[r2dbc-h2-0.8.4.RELEASE.jar:0.8.4.RELEASE]
at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:113) ~[reactor-core-3.4.9.jar:3.4.9]
... 44 common frames omitted
Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "CUSTOMER" already exists; SQL
statement:
CREATE TABLE CUSTOMER (id SERIAL PRIMARY KEY, name VARCHAR(255)) [42101-200]
As spring already created the table from the root location schema.sql, ConnectionFactoryInitializer bean is not needed. Removing the ConnectionFactoryInitializer bean declaration fixed the issue.

Error when adding custom revision in Hibernate envers

When I add custom revision entity, I start getting error:
2020-12-13 00:22:29.418 ERROR 80983 --- [ost-startStop-1] o.s.b.web.embedded.tomcat.TomcatStarter : Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating bean with name 'webSecurityConfig': Unsatisfied dependency expressed through field 'userDetailsService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsServiceImpl': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Cannot create inner bean '(inner bean)#4384acd' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#4384acd': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/resource/beans/spi/ManagedBeanRegistry
MyRevision:
package ...;
import org.hibernate.envers.DefaultRevisionEntity;
import org.hibernate.envers.RevisionEntity;
import javax.persistence.Entity;
#Entity
#RevisionEntity(MyRevisionListener.class)
public class MyRevision extends DefaultRevisionEntity {
private String username;
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
}
MyRevisionListener:
package ...;
// import de.xxxxx.carorderprocess.models.User;
import org.hibernate.envers.RevisionListener;
// import org.springframework.security.core.Authentication;
// import org.springframework.security.core.context.SecurityContext;
// import org.springframework.security.core.context.SecurityContextHolder;
// import java.util.Optional;
public class MyRevisionListener implements RevisionListener {
#Override
public void newRevision(Object revisionEntity) {
/* String currentUser = Optional.ofNullable(SecurityContextHolder.getContext())
.map(SecurityContext::getAuthentication)
.filter(Authentication::isAuthenticated)
.map(Authentication::getPrincipal)
.map(User.class::cast)
.map(User::getUsername)
.orElse("Unknown-User"); */
MyRevision audit = (MyRevision) revisionEntity;
audit.setUsername("dd");
}
}
WebSecurityConfig:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
UserDetailsServiceImpl userDetailsService;
UserDetailsServiceImpl:
#Service
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired
UserRepository userRepository;
#Override
#Transactional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User Not Found with username: " + username));
return UserDetailsImpl.build(user);
}
}
UserRepository:
#Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
Boolean existsByUsername(String username);
}
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>de.xxxxxxx</groupId>
<artifactId>carorderprocess</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>carorderprocess</name>
<description>Demo project for Spring Boot</description>
<dependencyManagement>
<dependencies>
</dependencies>
</dependencyManagement>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.16</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.5.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-envers</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>5.4.25.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
I think your problem could be related with the different dependencies in your pom.xml.
Please, first, remove the spring-data-envers dependency, unless you are querying your audit tables you do not need it. Even in that case, you can use Envers on its own to obtain that information if required.
Be aware that, as indicated in the comments of the answer from Sunit, you will need to remove the attribute repositoryFactoryBeanClass, it could not longer take the value EnversRevisionRepositoryFactoryBean. But you probably still need to include the #EnableJpaRepositories annotation.
Although I initially indicated that you can let Spring Boot manage your versions, due to the one of spring-boot-starter-parent, the framework is providing you versions of hibernate-xxx similar to 5.2.17.Final.
But, as you indicated, you need to use the method forRevisionsOfEntityWithChanges for querying your audit entities. As you can see in the java docs, that method was introduced in AuditQueryCreator in version 5.3.
As a consequence, you need to provide the following dependency:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>5.3.20.Final</version>
</dependency>
But in addition you also need to provide a compatible version of both hibernate-entitymanager and hibernate-core:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.3.20.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.20.Final</version>
</dependency>
From what I understood from all the comments above, your requirement is
to use Envers Auditing
and use method forRevisionsOfEntityWithChanges to get list of all revisions with what changed in them
Please start by doing these
Remove dependency of spring-data-envers library.
Just keep library hibernate-envers - version 5.4.23.Final also worked for me
Remove repositoryFactoryBeanClass = EnversRevisionRepositoryFactoryBean.class from #EnableJpaRepositories annotation
All Repository classes should only extend from JpaRespository and NOT from RevisionRepository. You dont need RevisionRepository
You should be able to get your application up and running now.
Now coming back to the question, how to get all revisions with changes using forRevisionsOfEntityWithChanges method.
Create an AuditConfiguration class like this, to create the AuditReader bean
#Configuration
public class AuditConfiguration {
private final EntityManagerFactory entityManagerFactory;
AuditConfiguration(EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
}
#Bean
AuditReader auditReader() {
return AuditReaderFactory.get(entityManagerFactory.createEntityManager());
}
}
In your AuditRevisionEntity class, add following annotation. Without this the serialization of this class wont work. e.g
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class AuditRevisionEntity extends DefaultRevisionEntity {
In your entity class add option withModifiedFlag = true to #Audited annotation. Without this you cannot get entity revisions with all changes. e.g
#Audited(withModifiedFlag = true)
public class Customer {
Modify your database table for this entity audit table and fields *_mod. e.g if you have a customer table with fields name, age, address columns, then add columns name_mod, age_mod, address_mod to the customer_audit table
Last, add following code in your service method to get audit revisions with changes
#Autowired
private AuditReader auditReader;
public List<?> getRevisions(Long id) {
AuditQuery auditQuery = auditReader.createQuery()
.forRevisionsOfEntityWithChanges(Customer.class, true)
.add(AuditEntity.id().eq(id));
return auditQuery.getResultList();
}
I will try to post the same code in Github sometime today, so that you can take a look at working code.
Your code looks fine. But it may not be sufficient to identify the root cause.
Looking at the exception it is clear that application is failing since it is not able to find bean dependency
Could you try following
Check your library imports first in your build.gradle or pom.xml. Generally you should not require any other Hibernate library other than Spring Boot Data JPA and Hibernate Envers
Try removing/disabling the Hibernate Envers audit code and library dependencies and see if can you get your application up and running. This will help you identify if error is due to Hibernate Envers or if your application code has other issues.
If above does not works, then please provide more information
Which version of Spring Boot are you on
What libraries have you imported (build.gradle or maven pom file)
What other Configurations you have in your project - do you have any other JPA configuration file or any other custom configuration related to Hibernate or JPA
What annotations are on the main application class
Directory structure of your Repository class, and the directory on which you do component scan (in case you have overridden it)

Spring - execute query before application shutdown (tests)

I'm running SpringBoot 2.1 with Sprind Data JPA/Hibernate as persistence layer. I run into problem to succesfully run query, in my tests, before application shutdown.
Details:
During application context startup I'm executing a query via JPA (let's say this query translates to following SQL "insert into mytable('mycolumn') values ('abc')).
Now I need to execute another query before application is shutdown. For given example this would be "update mytable set mycolumn = 'xyz' where mycolumn = 'abc'
I managed to execute the query by using #PreDestroy on my configuration class
#Configuration
MyConfig {
#Autowired
private MyTransactionalService myService;
#PreDestroy
public void doQuery() {
mySerivce.runMyQuery();
}
}
mySerivce.runMyQuery() delagates to myRepository (which is Spring Data JPA Repository) to call update query:
MyRepository extends JpaRepository(String, Something) {
#Modifying
#Query("UPDATE myEntity e SET e.myColumn = 'xyz' WHERE e.myColumn = 'abc")'
void runMyQuery();
}
The method annotated with #PreDestroy executes but when the query is executed by H2 (inmemory db running inside my spring tests) it throws exception saying that table does not exist.
The thing is that table surely existed before as I'm able to execute INSERT on that table during application startup (see beginning of the post).
My guess would be that the shudtown process is in progress, so the in-memory database was cleared out... thus there is no table.
Is there anyway to ensure query is executed while connection to database is still healthy and removal of tables did not happen yet (upon application context shutdown) ?
#Predestroy works as expected, just put #PreDestroy annotation on some method in you Application class. I created an example here. To test quickly i used sql files to initialize my database as it is described here, by you can also use a service for it. When i shutdown the application the database is updated as wanted. Please try :
Dependencies in : pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zpavel</groupId>
<artifactId>test</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
<version>1.4.199</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
</dependencies>
</project>
Model :
#Entity
#Data
public class Foo {
#Id
private Long id;
private String bar;
}
Repository :
public interface FooRepository extends JpaRepository<Foo, Long> {
}
src/main/resources/schema.sql :
DROP TABLE IF EXISTS foo;
CREATE TABLE foo (
id INT AUTO_INCREMENT PRIMARY KEY,
bar VARCHAR(250) NOT NULL
);
src/main/resources/data.sql :
INSERT INTO foo (bar) VALUES ('baz');
src/main/resources/application.properties :
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDBDialect
spring.datasource.url=jdbc:mariadb://localhost:3306/test?useSSL=false
spring.datasource.username=test
spring.datasource.password=test
spring.datasource.initialization-mode=always
Application.java
#SpringBootApplication
public class Application {
#Autowired
private FooRepository fooRepository;
// keep main method here
#PreDestroy
private void shutdown() {
fooRepository.deleteAll();
}
}
I managed to overcome this by using DB_CLOSE_ON_EXIT=FALSE"; init parameter
String url = "jdbc:h2:~/test;DB_CLOSE_ON_EXIT=FALSE";
In this case H2 does not kill the database and keeps it available during the shutdown process.

JPA Hibernate + UCP Oracle. Query executed from save method does not use the index of the table

I'm using the interface CRUDRepository in order to use the save method in other class where Repository is injected.
This method does an insert and a select for retrieve this object inserted from database, I mean.
The query executed is quite simple:
select auditoriab0_.adb_seqitm as adb_seqitm1_1_0_,
auditoriab0_.adb_codprv as adb_codprv2_1_0_, auditoriab0_.adb_ideses as adb_ideses3_1_0_,
auditoriab0_.adb_locata as adb_locata4_1_0_, auditoriab0_.adb_rqores as adb_rqores5_1_0_,
auditoriab0_.adb_rstime as adb_rstime6_1_0_, auditoriab0_.adb_subprv as adb_subprv7_1_0_,
auditoriab0_.adb_swierr as adb_swierr8_1_0_, auditoriab0_.adb_tiptrz as adb_tiptrz9_1_0_,
auditoriab0_.adb_ubitrz as adb_ubitrz10_1_0_, auditoriab0_.adb_xmltxt as adb_xmltxt11_1_0_
from nwt00.auditoria_bus_gsi auditoriab0_ where auditoriab0_.adb_seqitm=:p1
Where adb_seqitm column has and index on it (It's the table's primary key).
If this query is executed on SQLDeveloper, for instance, the explain plan is the correct one (access by rowid).
However, if this query is executed by hibernate, the result is a full scan.
Could you help me with this issue? I will be grateful because I don't have seen a real solution on internet for this specific problem.
Thank you in advance.
This behaviour happens with the ucp (universal connection pool) pool. My database bean configuration is the next (variables are setted by application.properties file):
UniversalConnectionPoolManager mgr;
try {
mgr = UniversalConnectionPoolManagerImpl. getUniversalConnectionPoolManager();
mgr.destroyConnectionPool("hotels");
} catch (UniversalConnectionPoolException e) {
}
PoolDataSourceImpl poolDataSource = (PoolDataSourceImpl) PoolDataSourceFactory.getPoolDataSource();
poolDataSource.setUser(userName);
poolDataSource.setPassword(passWord);
poolDataSource.setURL(url);
poolDataSource.setConnectionFactoryClassName(driver);
poolDataSource.setConnectionPoolName("hotels");
poolDataSource.setInitialPoolSize(initialNumConnections);
poolDataSource.setMinPoolSize(minNumConnections);
poolDataSource.setMaxPoolSize(maxNumConnections);
poolDataSource.setMaxConnectionReuseTime(reconnectTime);
poolDataSource.setMaxConnectionReuseCount(maxReconnectCount);
poolDataSource.setTimeToLiveConnectionTimeout(timeToLive);
poolDataSource.setConnectionWaitTimeout(connectWaitTimeOut);
poolDataSource.setValidateConnectionOnBorrow(true);
poolDataSource.setInactiveConnectionTimeout(inactiveConnectionTimeOut);
Properties properties = new Properties();
properties.put("v$session.program", "xxxx");
properties.put("defaultNChar", "false");
poolDataSource.setConnectionProperties(properties );
I'm using Spring Boot + Spring Data JPA. These are my dependencies of my pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.4.0</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ucp</artifactId>
<version>11.2.0.4.0</version>
</dependency>
#krokodilko As you anticipated, the error was between database type and java type. In DDBB, this field is a String (varchar2(15)). In Java, this field is mapped with a long type. I guess hibernate or database is doing a conversion which breaks the index. I have changed the java type by String type and query is working successfully. Explain plan is correct.

Resources