I have table which holds id
and 2 foreign keys. I need to add new record. Until persist
method everything goes as expected - productPart
is valid entity. After persist
is executed - no new records appear in MySQL table.
DAO
@Repository
public class ProductPartDao{
@Override
@Transactional
public void addProductPart (ProductPart productPart) {
sessionFactory.openSession().persist(productPart); // doesn't work
}
Service
@Service
public class ProductPartService{
@Autowired
ProductPartDao productPartDao;
@Override
@Transactional
public void addProductPart(ProductPart productPart) {
productPartDao.addProductPart(productPart);
}
I cannot use sessionFactory.getCurrentSession()
because it throws error: HibernateException: Could not obtain transaction-synchronized Session for current thread
.
What's the reason? How to solve it?
UPDATE
in applicationContext:
...
<tx:annotation-driven/>
...
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory">
</bean>
...
UPDATE2
Input is 2 id
which used to retrieve product
and part
objects. Then this objects set as fields to ProductPart
object and persisted. All retrieval methods for product
and part
is marked as @Transactional
. Why Spring and Hibernate are having trouble with it?
UPDATE3:
When code changed to sessionFactory.getCurrentSession()
there is exception:
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:988)
at ee.t.mysql.model.ProductPartDAOImpl.addProductPart(ProductPartDAOImpl.java:19)
The session object just before Exception:
It can persist object when it's called from main with loaded ConfigurableApplicationContext
. Spring web application with controllers fails.
SOLVED
Solved by replacing sessionFactory.openStatelessSession().insert(...)
. I have no idea how and why it works. An explanation would be greatly appreciated!