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?
The @Transactional annotation belongs to the Service layer because it is the Service layer's responsibility to define the transaction boundaries.
Generally the DAO is as light as possible and exists solely to provide a connection to the DB, sometimes abstracted so different DB backends can be used. The service layer is there to provide logic to operate on the data sent to and from the DAO and the client.
The Spring Framework enables declarative transaction management to be applied to any class, not merely special classes such as EJBs. The Spring Framework offers declarative rollback rules: this is a feature with no EJB equivalent. Both programmatic and declarative support for rollback rules is provided.
DAO stands for data access object. Usually, the DAO class is responsible for two concepts: encapsulating the details of the persistence layer and providing a CRUD interface for a single entity.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With