I have bellow code stuffs and I'm using spring and hibernate
//main method in main class
public static void main(String[] args) {
String[] path = new String[]{"applicationContext.xml"};
ApplicationContext context = new ClassPathXmlApplicationContext(path);
serviceObj = (ServiceClassType)context.getBean("serviceBean");
serviceObj.doTask();
}
//service method in service class
doTask(){
Obj obj=new Obj();
obj.setValue1("value1");
obj.setValue2("value2");
myDao.saveObject(obj);
}
//in dao class //scenario #1
saveObject(Obj obj){
gethibernatetemplate().save(obj);
}
//scenario #2
saveObject(Obj obj){
session = getHibernateTemplate().getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
session.save(obj);
tx.commit();
}
***scenario #1 does not persists data but scenario #2 working fine. Can someone explain why?
Hibernate Session doesn't work without Transaction in standart configuration. If you add this property
<property name="connection.autocommit">true</property>
scenario #1 will work .
Because Hibernate doesn't commit the transaction by default. I would recommend to use Spring's Transaction Manager to handle this logic, instead of manual commit/rollback. It automatically commits transaction if everything went fine, and rollbacks the transaction in case of any error. With correct Spring configuration your code will look like:
class ServiceClassType {
@Transactional
public doTask(){
// update entities with your DAO classes
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.