简体   繁体   English

服务中的Spring事务和DAO层

[英]Spring transaction in service and DAO layers

In my example I have one Hibernate entity and one DAO. 在我的例子中,我有一个Hibernate实体和一个DAO。

@Entity
@Table(name="myEntity")
public class MyEntity {

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id")
    private long id;

    @Column(name="action")
    private String actionName;

}

...................

@Repository("myDAO")
@Transactional(propagation = Propagation.REQUIRED)
public class MyDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void saveObject(MyEntity myEntity){
        sessionFactory.getCurrentSession().save(myEntity);
    }

}

When I use DAO in Service in such a manner 当我以这种方式在服务中使用DAO时

@Service("myService")
@Transactional(propagation = Propagation.REQUIRED)
public class MyService 
{

    @Autowired
    private MyDAO myDAO;

    public void executeTransaction(){
        MyEntity myEntity = new MyEntity();

        myEntity.setActionName("Action1");
        myDAO.saveObject(myEntity);

//      myEntity = new MyEntity();
        myEntity.setActionName("Action2");
        myDAO.saveObject(myEntity);
    }

}

only one row(Action2) is saved in database. 数据库中只保存一行(Action2)。 When I remove comment both rows(Action1 and Action2) are saved(this is behaviour that I need). 当我删除注释时,两行(Action1和Action2)都被保存(这是我需要的行为)。 My question is how Transactional annotation on service layer influences on transaction(method executeTransaction()) execution. 我的问题是服务层上的Transactional注释如何影响事务(方法executeTransaction())执行。 Why without Transactional annotation on service layer both rows are saved in database and only last is saved with this annotation? 为什么没有服务层上的Transactional注释,两行都保存在数据库中,只有最后一行保存在这个注释中?

Without myEntity = new MyEntity(); 没有myEntity = new MyEntity(); your record in the database is updated, not inserted, because it's the same entity. 您在数据库中的记录是更新的,而不是插入的,因为它是同一个实体。 I sugest to set <property name="show_sql">true</property> in the hibernate conf. 我在hibernate conf中设置<property name="show_sql">true</property> This will show you what is happening. 这将告诉你发生了什么。

Two different records will only be saved in database when you will store two different objects. 当您存储两个不同的对象时,两个不同的记录将仅保存在数据库中。 When you have commented that line, you are setting (means updating) properties in the same object. 当您注释该行时,您在同一对象中设置(表示更新)属性。 So, hibernate will update the same row, instead of creating a new one. 因此,hibernate将更新同一行,而不是创建一个新行。 But, when you uncomment that line, you are creating a new instance, which is not already persisted. 但是,当您取消注释该行时,您正在创建一个尚未保留的新实例。 So, it will result in a new row being inserted in the database. 因此,它将导致在数据库中插入新行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM