Question

In my example I have one Hibernate entity and one 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

@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. When I remove comment both rows(Action1 and Action2) are saved(this is behaviour that I need). My question is how Transactional annotation on service layer influences on transaction(method executeTransaction()) execution. Why without Transactional annotation on service layer both rows are saved in database and only last is saved with this annotation?

Was it helpful?

Solution

Without 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. This will show you what is happening.

OTHER TIPS

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. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top