persistence in hsqldb with spring - spring

I'm struggling with persistence with spring and hsqldb. I checked out several questions but couldn't manage to find a solution:
Threads checked out:
No schema in file database after running program persisted to hsqldb:file via hibernate
HSQLDB and Hibernate/JPA - not persisting to disk?
Hibernate doesn't save any records in database
However this didn't help so far. Everytime I restart my webserver all changes are gone and nothing is written to my harddisk.
Hibernate configuration is as follows
#Bean
public AnnotationSessionFactoryBean sessionFactoryBean() {
Properties props = new Properties();
props.put("hibernate.dialect", HSQLDialect.class.getName());
props.put("hibernate.format_sql", "true");
props.put("hibernate.show_sql", "true");
props.put("hibernate.hbm2ddl.auto", "update");
props.put("hibernate.connection.url", "jdbc:hsqldb:file:c:\\temp\\rvec");
props.put("hibernate.connection.username", "sa");
props.put("hibernate.connection.password", "");
props.put("hibernate.connection.pool_size","1");
props.put("hibernate.connection.autocommit", "true");
AnnotationSessionFactoryBean bean = new AnnotationSessionFactoryBean();
bean.setAnnotatedClasses(new Class[]{Course.class, User.class, Event.class});
bean.setHibernateProperties(props);
bean.setDataSource(this.dataSource);
bean.setSchemaUpdate(true);
return bean;
}
data source and transaction manager are configured in servlet-context.xml
<tx:annotation-driven transaction-manager="transactionManager" />
There are no errors thrown in the console but only valid sql statements.
Any ideas?
Kind regards,
Lomu

Related

Transactions, Spring Boot Starter JDBC & R2DBC

I am trying to migrate a Spring Boot project, version 2.3.0.M3, that have used JDBC template to R2DBC. The project also uses Liquibase so I cannot get rid of JDBC altogether.
I have both the spring-boot-starter-data-r2dbc and the spring-boot-starter-jdbc dependencies in the project with which I get the following exception when trying to run one of my tests:
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.springframework.transaction.TransactionManager' available: expected single matching bean but found 2: transactionManager,connectionFactoryTransactionManager
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveNamedBean(DefaultListableBeanFactory.java:1180)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveBean(DefaultListableBeanFactory.java:416)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:349)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:342)
at org.springframework.transaction.interceptor.TransactionAspectSupport.determineTransactionManager(TransactionAspectSupport.java:480)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:335)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:99)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689)
...
The bean connectionFactoryTransaction manager is defined like this in the Spring class R2dbcTransactionManagerAutoConfiguration:
#Bean
#ConditionalOnMissingBean(ReactiveTransactionManager.class)
public R2dbcTransactionManager connectionFactoryTransactionManager(ConnectionFactory connectionFactory) {
return new R2dbcTransactionManager(connectionFactory);
}
The bean transactionManager is defined like this in the Spring class DataSourceTransactionManagerAutoConfiguration:
#Bean
#ConditionalOnMissingBean(PlatformTransactionManager.class)
DataSourceTransactionManager transactionManager(DataSource dataSource,
ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);
transactionManagerCustomizers.ifAvailable((customizers) -> customizers.customize(transactionManager));
return transactionManager;
}
As can be seen, the #ConditionalOnMissingBean annotation contains different types which will cause an instance of both beans to be created.
However, in the Spring class TransactionAspectSupport there is this line of code in the determineTransactionManager method:
defaultTransactionManager = this.beanFactory.getBean(TransactionManager.class);
Since both of the transaction manager types, DataSourceTransactionManager and R2dbcTransactionManager, implement the TransactionManager interface, both the transaction manager beans as above will be matched and the error will occur.
I am now reaching out to hear if there is anyone who has managed to solve or work around this issue?
Thanks in advance!
With inspiration from M. Deinums answer (thanks!), I applied the following steps to my project and the test that failed earlier now runs successfully:
Remove the spring-boot-starter-jdbc dependency.
Add a dependency to spring-jdbc.
Add a dependency to HikariCP (com.zaxxer).
Add spring.liquibase user and password properties (I already had the url and change-log properties).
Remove all spring.datasource properties (I had url and drive-class-name).
I had the spring.r2dbc properties username, password and url defined which I did not need to change.
Update:
In addition, I used Testcontainers in the tests and could not assign a static port. In order to be able to configure the database port on Liquibase, I overrode a bean name liquibase of the type SpringLiquibase and created a DataSource (not exposed as a bean) in the liquibase bean creation method and set it on the liquibase bean.
It's possible to have spring-boot-starter-jdbc and spring-boot-starter-data-r2dbc co-exist. There is a class org.springframework.transaction.annotation.TransactionManagementConfigurer that can be used to resolve the conflict.
Spring Boot 2.3.0 seems to disable automatic datasource config when r2dbc is present. It's possible to manually import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration class to make both co-exist.
#Bean
TransactionManagementConfigurer transactionManagementConfigurer(ReactiveTransactionManager reactiveTransactionManager) {
return new TransactionManagementConfigurer() {
#Override
public TransactionManager annotationDrivenTransactionManager() {
return reactiveTransactionManager;
}
};
}

Failed to get driver instance for oracle

I’m trying to connect to my oracle database, I’m using a spring boot configuration together with YAML file, I’ve configured jdbc in pom and jpa, but it still fails to connect.
I’ve tried many different configuration for the url:
1) jdbcUrl=jdbc:oracle:thin://test.test.test:1521
2) jdbcUrl=jdbc:oracle:thin#test.test.test:1521
3) jdbcUrl=jdbc:oracle://test.test.test:1521
4) jdbcUrl=jdbc:oracle#test.test.test:1521
here my application.yml
spring:
profiles: test
datasource:
onlineterminierung:
url: jdbc:oracle: jdbc:oracle:thin://test.test.test:1521
database: test
username: test
password: test
driverClassName: oracle.jdbc.driver.OracleDriver
defaultSchema:
maxPoolSize: 20
hibernate:
hbm2ddl.method: update
show_sql: false
format_sql: true
dialect: org.hibernate.dialect.Oracle10gDialect
and here the DataSource bean:
/*
* Configure HikariCP pooled DataSource.
*/
#Bean
public DataSource dataSource() {
DataSourceProperties dataSourceProperties = dataSourceProperties();
HikariDataSource dataSource = (HikariDataSource) DataSourceBuilder.create(dataSourceProperties.getClassLoader())
.driverClassName(dataSourceProperties.getDriverClassName()).url(dataSourceProperties.getUrl()).username(dataSourceProperties.getUsername())
.password(dataSourceProperties.getPassword()).type(HikariDataSource.class).build();
dataSource.setMaximumPoolSize(maxPoolSize);
return dataSource;
}
here the pom:
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.3.0</version>
<scope>test</scope>
</dependency>
here the stack:
HHH000342: Could not obtain connection to query metadata : Failed to get driver instance for jdbcUrl=jdbc:oracle:thin://test.test.test:1521
Unable to build Hibernate SessionFactory
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
Caused by: java.lang.RuntimeException: Failed to get driver instance for jdbcUrl=jdbc:oracle:thin://test.test.test:1521
Caused by: java.sql.SQLException: No suitable driver
Some idea?
Syntax:
jdbc:oracle:thin:#host:port:db","usname","pwd"
#Autowired
DataSource dataSource;
#Bean(name = "dataSource")
public DriverManagerDataSource dataSource() {
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setDriverClassName("oracle.jdbc.OracleDriver");
driverManagerDataSource.setUrl("jdbc:oracle:thin:#hostname:1521/dbname");
driverManagerDataSource.setUsername("uname");
driverManagerDataSource.setConnectionProperties(getadditionalJpaProperties());
driverManagerDataSource.setPassword("password");
return driverManagerDataSource;
}
Properties getadditionalJpaProperties() {
Properties properties = new Properties();
// properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
properties.setProperty("hibernate.show_sql", "true");
return properties;
}
Always use the long form of the connection URL that gives you the flexibility to pass various connection level parameters. A code sample DataSourceSample on GitHub has a sample URL for reference.
jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS=(HOST=myhost)(PORT=1521)(PROTOCOL=tcp))(CONNECT_DATA=(SERVICE_NAME=myorcldbservicename)))";
I ran into this problem. and I was mistakenly ignoring a line of code
driverManagerDataSource.setDriverClassName("oracle.jdbc.OracleDriver");
or in bean config
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
I am using Oracle 11G and Jersey + Boot server running on Websphere

Weblogic jndi NameNotFoundException occur with java config

I been searching again for this issue where I cannot locate the jndi database by using java config. Before this I use xml and its work perfectly but in java config it cause an issue;
Xml code:
<!-- Jndi database connection -->
<jee:jndi-lookup id="dbDataSource" jndi-name="${db.jndi}"
resource-ref="true" />
<beans:bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate" >
<beans:property name="dataSource" ref="dbDataSource"></beans:property>
</beans:bean>
Java config now:
#Bean(name = "dbDataSource")
public DataSource dataSource(#Value("${db.jndi}") String jndiName)
{
JndiDataSourceLookup lookup = new JndiDataSourceLookup();
return lookup.getDataSource(jndiName);
}
#Bean
public JdbcTemplate jdbcTemplate(DataSource ds) {
return new JdbcTemplate(ds);
}
Properties file:
db.jndi=jndi/myData
JNDI name in weblogic:
jndi/myData
After change to java config, sometimes the system can read the database but rarely occur, until I clean and restart my computer then it can find the database, but usually its always trigger:
javax.naming.NameNotFoundException: Unable to resolve 'jndi.myData'. Resolved 'jndi'; remaining name 'myData'
Why the application cannot find the database correctly?
Thanks!!!
I've had the same issue. If you're using 4.x version of spring that's probably the cause.
You should also check Weblogic's JNDI Tree. If your data source disapears from the tree after rebuilding the project, that's another symptom
If that's the case, what's happening is:
Your Datasource implements Closeable (and therefore AutoCloseable) and the context will always invoke the shutdown method regardless of your Bean definition
as seen here : SPR-12551: Document how to prevent a JNDI DataSource retrieved using JavaConfig to be removed on shutdown of the context
It's been marked as a documentation issue as this is the "expected" behaviour:
This issue was solely about documentation since we decided not to implement anything at the framework level
the solution, is to define the destroy method of the bean as empty, such as:
#Bean(name = "dbDataSource", destroyMethod="")
public DataSource dataSource(#Value("${db.jndi}") String jndiName)
{
JndiDataSourceLookup lookup = new JndiDataSourceLookup();
return lookup.getDataSource(jndiName);
}
#Bean
public JdbcTemplate jdbcTemplate(DataSource ds) {
return new JdbcTemplate(ds);
}
This is described in this issue (SPR-13022:Destroy callback cannot be disabled for AutoCloseable beans) .
PS: By the way, it seems like on early 4.x version of spring you couldn't override this behaviour by assingning destroyMethod. It apears that this bug was fixed on version 4.2 RC1.
I've had the same issue and I solved problem. I used to jndi datasource on weblogic. After I restart application, I notice my jndi datasource remove from Weblogic's JNDI Tree. Xml configuration works successfuly but java configuration don't work.
My old spring version: 4.1.6.RELEASE Upgrade to 4.3.9.RELEASE
Xml configuration like this;
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>${db-jndi.name}</value>
</property>
</bean>
Java configuration like this;
#Bean(name = "dataSource")
public DataSource dataSource() throws IllegalArgumentException, NamingException
{
JndiTemplate jndiTemplate = new JndiTemplate();
DataSource dataSource = (DataSource) jndiTemplate.lookup(env.getProperty("db-jndi.name"));
logger.info("DataSource initialized in jndi ");
return dataSource;
}
Then i changed
#Bean(name = "dataSource")
to
#Bean(name = "dataSource", destroyMethod = "")
And it's works successfuly.
It looks like your datasource hasn't been deployed. You should look for JNDI tree for the server you tried to deploy datasource. (https://docs.oracle.com/cd/E12839_01/apirefs.1111/e13952/taskhelp/jndi/ViewObjectsInTheJNDITree.html) If you don't see "jndi.myData" on JNDI tree, you can assume that your datasource haven't been deployed. So you can go to your datasource monitoring tab and test the datasource. (https://docs.oracle.com/cd/E17904_01/apirefs.1111/e13952/taskhelp/jdbc/jdbc_datasources/TestDataSources.html)

Use context parameters in junit test case

In Spring,how to use context paramters in the tomcat location conf/context.xml in the junit testing or how to create context parameters in junit
<Context>
<Parameter name="mail_host" value="smtp.gmail.com" override="true"/>
</Context>
I am implementing the above parameters in my code as i specified below
#Value("#{contextParameters.mail_host}").It is working fine when i am using tomcat.
But i am getting an error 'Field or property 'contextParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext'
when running in junit
Please help me,I am struggling in this point.Thanks in advance
You could construct JNDI before you run your test and in your test you can retrieve the information from context. Take a look a this example how he simulates injecting datasource using jndi here.
And your context would look something like this(in actual tomcat)
<Resource name="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource"
username="root"
password="password"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mysql"/>
So now we want to simulate this as if we would retrieve it using JNDI.
So in JUnit test cast we would like to setup Before class.Please note that not all information is shown here(constructing the datasource in #Before), but you got the point.
#BeforeClass
public static void setUpClass() throws Exception {
// rcarver - setup the jndi context and the datasource
try {
// Create initial context
System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"org.apache.naming.java.javaURLContextFactory");
System.setProperty(Context.URL_PKG_PREFIXES,
"org.apache.naming");
InitialContext ic = new InitialContext();
ic.createSubcontext("java:");
ic.createSubcontext("java:/comp");
ic.createSubcontext("java:/comp/env");
ic.createSubcontext("java:/comp/env/jdbc");
// Construct DataSource
OracleConnectionPoolDataSource ds = new OracleConnectionPoolDataSource();
ds.setURL("jdbc:oracle:thin:#host:port:db");
ds.setUser("MY_USER_NAME");
ds.setPassword("MY_USER_PASSWORD");
ic.bind("java:/comp/env/jdbc/nameofmyjdbcresource", ds);
} catch (NamingException ex) {
Logger.getLogger(MyDAOTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
and in your test you can get this information
Context initContext = new InitialContext();
Context webContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource) webContext.lookup("jdbc/nameofmyjdbcresource");
Hope it helps.
EDIT
e.g.
MyMailHost mailHost = new MyMailHost();
mailHost.setName("mail_host");
mailHost.setValue("smtp.gmail.com");
mailHost.setOverride(true);
ic.bind("java:/comp/env/jdbc/mymailhost", mailHost);
in #Test
Context initContext = new InitialContext();
Context webContext = (Context)initContext.lookup("java:/comp/env");
MyMailHost ds = (MyMailHost) webContext.lookup("jdbc/mymailhost");
One solution that I've used is to stub the context parameters in my test spring applicationContext file with a simple properties bean.
So in your case:
<util:properties id="contextParameters">
<prop key="mail_host">smtp.gmail.com</prop>
</util:properties>
This is the easiest way to handle it.
Hope it helps!

What's the Java configuration version of jpa:repositories tag?

I'm trying to configure JPA using just Java.
I got the idea that #EnableJpaRepositories would be the equivalent of jpa:repositories tag in xml, but I guess this is not the case?
I have this in my xml:
<jpa:repositories base-package="com.myapp.bla.bla" />
But if I remove it and instead use
#EnableJpaRepositories("com.myapp.bla.bla")
In my java config, I get an exception - I thought it was possible to configure JPA with Java since 1.2.0?
EDIT:
The root exception is:
No bean named 'entityManagerFactory' is defined
I assume the exception has to do with this definition in my config, but as said, everything works if I keep the xml and import it to my java config.
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() throws ClassNotFoundException {
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(dataSource());
factoryBean.setPackagesToScan(new String[] { "com.myapp.bla.bla.model" });
factoryBean.setPersistenceProviderClass(HibernatePersistence.class);
Properties props = new Properties();
props.put("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
factoryBean.setJpaProperties(props);
return factoryBean;
}
The problem is that your current configuration creates a bean called entityManagerFactoryBean. However, the error message of your root exception says that a bean named entityManagerFactory is not found.
You have two options for fixing this problem (pick the one you like the most):
Change the name of the method which configures the LocalContainerEntityManagerFactoryBean from entityManagerFactoryBean() to entityManagerFactory(). This creates a bean named entityManagerFactory.
Set the name attribute of the #Bean annotation to "entityManagerFactory". In other words, annotate the configuration method with #Bean(name="entityManagerFactory") annotation. This way you can specify the name of bean yourself and ensure that the name of the annotated method is ignored.

Resources