We want to get all the records in Database using HQL in terms of Spring and Hibernate - spring

Here i tried 2 write cod 2 get list from Mysql Database using spring nd Hibernate.
But problem is here that how initialize **org.hibernate.Session se through "applicationContext.xml" file by bean class....
public void getList(**Session se**){
String liststudent="from StudentList stud";
Query q=se.createQuery(liststudent);
List<Object> list=q.list();
for(Object obj:list){
Object studarr[]=(Object[])obj;
System.out.println("Data at Zero Index"+studarr[0]);
}
}
As here property name **template** has been initialized by the ref template.
Is there any way to initialize Session se.
<bean name="mydao" class="dao.MyDao">
<property name="template" ref="template"></property>
</bean>

using your context.xml file
define sessionFactory
<bean id="sessionFactory" class="LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--define other properties...mapping files
</bean>
define hibernateTemplate
<bean id="template" class="*HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
then
<bean name="mydao" class="dao.MyDao">
<property name="template" ref="template"></property>
</bean>
NOTE: the class package has been ommitted

Related

How to configure multiple MyBatis datasources in Spring Boot?

With MyBatis-Spring-Boot-Starter, we can easily integrate MyBatis with Spring Boot, it works perfectly for one data source. However, now we'd like to add an extra data source in our project, unfortunately it seems not easy.
In MyBatis official documentation, I see the following content:
MyBatis-Spring-Boot-Starter will:
Autodetect an existing DataSource.
Will create and register an instance of a SqlSessionFactoryBean passing that DataSource as an input.
Will create and register an instance of a SqlSessionTemplate got out of the SqlSessionFactoryBean.
It looks like MyBatis-Spring-Boot-Starter supports only one data source at this moment. So, the question is how to configure multiple MyBatis datasources in Sping Boot?
You outlined 3 beans that are needed for MyBatis+Spring integration. These are automatically created for single data source.
If you need two data sources, you need to create 3 beans for each data source explicitly. So you'll be creating 6 beans (2 of type DataSource, 2 of type SqlSessionFactoryBean and 2 of type SqlSessionFactoryBean).
To bind DAO with certain datasource, you will need to use sqlSessionTemplateRef or sqlSessionFactoryRef parameter of #MapperScan annotation.
Also I don't recommend to go down the XML hell. I was using it this way in PROD, with two data sources, without any ugly XML configs on various projects. Also SQL queries were annotated.
Shame is that MyBatis documentation is not great and most examples out there are in XML.
Something this like this to your spring servlet.xml:
<bean id="db2dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName"><value>${db2.database.driver}</value></property>
<property name="url"><value>${db2.database.url}</value></property>
<property name="username"><value>${db2.database.username}</value></property>
<property name="password"><value>${db2.database.password}</value></property>
<property name="maxActive"><value>${db2.database.maxactiveconnections}</value></property>
<property name="maxIdle"><value>${db2.database.idleconnections}</value></property>
<property name="initialSize"><value>${db2.database.initialSize}</value></property>
</bean>
<bean id="db2SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="db2dataSource" />
<property name="configLocation" value="/WEB-INF/mybatis-config.xml"/>
</bean>
<bean id="db2Dao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="sqlSessionFactory" ref="db2SqlSessionFactory"/>
<property name="mapperInterface" value="com.dao.db2Dao" />
</bean>
<bean id="oracledataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName"><value>${oracle.database.driver}</value></property>
<property name="url"><value>${oracle.database.url}</value></property>
<property name="username"><value>${oracle.database.username}</value></property>
<property name="password"><value>${oracle.database.password}</value></property>
<property name="maxActive"><value>${oracle.database.maxactiveconnections}</value></property>
<property name="maxIdle"><value>${oracle.database.idleconnections}</value></property>
<property name="initialSize"><value>${oracle.database.initialSize}</value></property>
</bean>
<bean id="oracleSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="oracledataSource" />
<property name="configLocation" value="/WEB-INF/mybatis-config.xml"/>
</bean>
<bean id="oracleoardDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="sqlSessionFactory" ref="oracleSqlSessionFactory"/>
<property name="mapperInterface" value="com.lodige.clcs.dao.oracleoardDao" />
</bean>
Maybe this is what you need
#Configuration
#MapperScan(basePackages = "com.neo.mapper.test1", sqlSessionTemplateRef =
"test1SqlSessionTemplate")
public class DataSource1Config {
#Bean(name = "test1DataSource")
#ConfigurationProperties(prefix = "spring.datasource.test1")
#Primary
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
#Bean(name = "test1SqlSessionFactory")
#Primary
public SqlSessionFactory testSqlSessionFactory(#Qualifier("test1DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
}
#Bean(name = "test1TransactionManager")
#Primary
public DataSourceTransactionManager testTransactionManager(#Qualifier("test1DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
#Bean(name = "test1SqlSessionTemplate")
#Primary
public SqlSessionTemplate testSqlSessionTemplate(#Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}

Data is not getting inserted in JPA Spring weblogic

I have following configuration in application context
<jee:jndi-lookup id="dataSource" jndi-name="MY_DS" />
<context:load-time-weaver/>
<bean id="transactionManager" class="org.springframework.transaction.jta.WebLogicJtaTransactionManager" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="emf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jtaDataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="persistenceUnitName" value="pu_TEST" />
</bean>
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="database" value="ORACLE" />
<property name="showSql" value="true" />
</bean>
Now my DAO Class
#Repository
public class EmployeeDAO{
#PersistenceContext
private EntityManager em;
#Transactional
public void create(Employee entity) {
LOG.error("Enitity Manager:create" + em);
em.persist(entity);
// em.flush(); if i use flush it saves
}
}
Now when I save the entity it does not say give any error but no data is updated into db.
I do not wish to use flush as entitymanager is injected by spring and should perform flush at the end automatically which is not happening. correct my understanding.
Adding facade class may be issue is there, Does Propagation.REQUIRES_NEW has anything to do here?
#Transactional(propagation=Propagation.REQUIRES_NEW)
public void process(){
Employee e = factory.getEmployee();
employeeDao.create(e);
}
On Debug after create method call it shows employee got primary key populated that mean db call has made but at the end it is not persisted.
Please try either of the 3 :
1.Solution 1
Please call below code
em.joinTransaction();
just before
em.persistEntity(entity);
2.Solution 2
make attribute readOnly=false in #Transactional
3.Solution 3
Try manually adding bean EmployeeDAO in spring xml file
or else you can try below:
#Transactional(propagation=Propagation.REQUIRED)

Multiple SharedEntityManagerBeans and ApplicationContext.getBean issue

I have two databases which I want to access from my Spring application. I configured two SharedEntityManagerBean for both databases. Here is the config:
<jpa:repositories base-package="xxx" entity-manager-factory-ref="entityManagerFactory1" />
<jpa:repositories base-package="xxx" entity-manager-factory-ref="entityManagerFactory2" />
<tx:annotation-driven/>
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
id="transactionManager1">
<property name="entityManagerFactory" ref="entityManagerFactory1" />
<property name="dataSource" ref="dataSource1" />
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
id="transactionManager2">
<property name="entityManagerFactory" ref="entityManagerFactory2" />
<property name="dataSource" ref="dataSource2" />
</bean>
<bean id="entityManagerFactory1"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:packagesToScan="xxxxxx"
....
</bean>
<bean id="entityManagerFactory2"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:packagesToScan="xxxxx"
...
</bean>
<bean id="entityManager1" class="org.springframework.orm.jpa.support.SharedEntityManagerBean" >
<property name="entityManagerFactory" ref="entityManagerFactory1" />
</bean>
<bean id="entityManager2" class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory2" />
</bean>
<bean id="dataSource1"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
...
</bean>
<bean id="dataSourceOntology"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
...
</bean>
I have two EntityLocators which are not managed by Spring that access entities in each of the corresponding databases. They look something like that:
public class SpringEntitiyLocator1 {
private EntityManager em;
public SpringEntitiyLocator1() {
}
private EntityManager getEM() {
if (em == null) {
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(RequestFactoryServlet.getThreadLocalServletContext());
SharedEntityManagerBean bean = context.getBean("entityManager1",SharedEntityManagerBean.class);
em = bean.getObject();
}
return em;
}
}
When I have only one SharedEntityManagerBean defined in my applicationContext the call to getBean() works fine. However once I have both SharedEntityManagerBeans defined I get the error:
Bean named 'x' must be of type [y], but was actually of type [$Proxy]
I read on SO that I should use cglib proxying by adding <aop:config proxy-target-class="true"/> to my application.xml.
Is that the best solution ?
When I add that line I get Caused by: java.lang.NoClassDefFoundError: org/aspectj/util/PartialOrder$PartialComparable errors.
Do I need aspectj for that?
EDIT:
In case I have only one SharedEntityManagerBean defined I can call getBean(SharedEntityManagerBean.class). This works fine.
I debugged the code and it seems that this call will call getBean("&entityManager1",SharedEntityManagerBean.class) (note &) .
However when I pass the name getBean("EntityManager1",SharedEntityManagerBean.class) I get a type cast exception.
Having both SharedEntityManagerBeans defined and call getBean without a name also causes an exception (can't find a bean with that name).
So my current workaround is to call: getBean("&entityManager1",SharedEntityManagerBean.class) and getBean("&entityManager2",SharedEntityManagerBean.class)
This works fine.
Ok apparently SharedEntityManagerBean is a FactoryBean and for that I have to add & before the bean name to retrieve the SharedEntityManagerBean.
Alternatively I could probably just call:
em = context.getBean("entityManager",EntityManager.class);
See here and here for reference.

Spring JUnit JPA Transaction not rolling back

I am trying to test my DAO that uses JPA EntityManager to fetch and update entities. I have marked my unit test as Transactional and set the defaultRollback property to false. However, I don't see my transactions rolling back at the end of the test when throwing a rune time exception. The data is getting persisted in the DB. Here is my unit test code along with spring configuration. I am clearly missing something but havent been able to identify what.
Btw, the transaction is RESOURCE_LOCAL in the persistence.xml
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"classpath:spring/test-jpa.xml"})
#TestExecutionListeners(
{ DependencyInjectionTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class
})
#TransactionConfiguration(defaultRollback=false)
#Transactional
public class JpaTests {
#PersistenceContext
EntityManage em;
#Test
public void testTransactionQueueManager() {
Object entity = em.find(1);
//code to update entity omitted.
entity = em.merge(entity);
em.flush();
throw new RuntimeException
}
}
Spring Configuration
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jpa.driverclassname}" />
<property name="url" value="${jpa.url}" />
<property name="username" value="${jpa.username}" />
<property name="password" value="${jpa.password}" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="${jpa.persistenceunitname}"/>
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter">
<property name="databasePlatform" value="org.apache.openjpa.jdbc.sql.DBDictionary"/>
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
Your configuration seems fine.
There could be different reasons for the unexpected commit, maybe a datasource with autocommit mode or a non transaction compliant database (mysql with MyISAM ?)
Did you check this thread Why are transactions not rolling back when using SpringJUnit4ClassRunner/MySQL/Spring/Hibernate ?
#TransactionConfiguration(defaultRollback=false)
might be the culprit. Try defaultRollback=true, that should rollback the transaction.
Adding rollbackFor may help, it's a common pitfall.
#Transactional(rollbackFor=Exception.class)

Spring + Hibernate + JPA + 2 databases. persist silently fails to commits with #Transactional annotation

My setup is Spring MVC 3.1, Hibernate 4.1 with two databases.
My service methods seem to work fine for reads (for both dbs). But the persist fails to insert the data in the db - and no exception in the logs at all. Looking at the sql output of hibernate it looks like it did retrieve the newly generated id but then never did the insert - if it did it doesn't show in the db nor was an insert logged in the log file. In the db I can see the sequence number is incremented but no data was inserted. I couldn't figure out what is wrong with my config. Hopefully someone has an idea.
Below are the relevant pieces from config file
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
</bean>
<bean id="mgrFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource">
<property name="packagesToScan" value="xxx.yyy" />
<property name="persistenceUnitName" value="puOne"/>
<property name="persistenceProviderClass" value="org.hibernate.ejb.HibernatePersistence"/>
</property>
</bean>
<tx:annotation-driven mode="aspectj" transaction-manager="txMgr"/>
<bean id="txMgr"
class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="mgrFactory">
</bean>
This works fine as it is. What I want to do now is add the ability to use another database. So I added another data source, entity manager factory and transaction manager
<bean id="dataSourceTwo" class="org.apache.commons.dbcp.BasicDataSource">
</bean>
<bean id="mgrFactoryTwo"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSourceTwo">
<property name="packagesToScan" value="xxx.zzz" />
<property name="persistenceUnitName" value="puTwo"/>
<property name="persistenceProviderClass" value="org.hibernate.ejb.HibernatePersistence"/>
</property>
</bean>
<tx:annotation-driven mode="aspectj" transaction-manager="txMgrTwo"/>
<bean id="txMgrTwo"
class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="mgrFactoryTwo">
</bean>
I also made sure that the two respective base DAOs annotate their entity manager's with the unit name like
#PersistenceContext(unitName = "puOne")
protected EntityManager entityManager;
The last thing I did was to add the transaction manager names inside my #Transactional annotations inside my services like
#Override
#Transactional(value="txMgrTwo" propagation = Propagation.REQUIRED)
public boolean create(User user) {
userDao.persist(user);
}

Resources