问题描述:

I have a problem with saving my entity, i use spring 4 and hibernate 4.

 @Repository

public class AuthDao {

@Autowired

private SessionFactory sessionFactory;

@Transactional

public void enregistrer(Auth auth) {

Session session = sessionFactory.openSession();

session.saveOrUpdate(auth);

}

No entry in my database was added.

But if i want just read it's okey.

session.get(Auth.class, 2)

my second problem is i want understand why when i put:

Session session = sessionFactory.getCurrentSession();

it doesn't work and i got :

No Session found for current thread

my other files:

@Controller

public class testController {

@Autowired

private AuthDao authDao;

@RequestMapping(value = "/cc")

public String printWelcome() {

authDao.enregistrer(new Auth(7, "test", "test"));

return "hello";

}

}

 <context:component-scan base-package="dao"/>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

...

</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

...

</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">

<property name="sessionFactory" ref="sessionFactory"/>

</bean>

网友答案:

The first question: the HibernateSession is a first level cache, the data will not saved (in data base) until the session is closed (tipically in the commit transaction), but data are accesible for some queries. This link explain it very well.

The second question: You are asking for the current HibernateSession, but is possible that is not accessible because it has not been created or opened.

In my personal opinion, this isn't the best way to integrate Spring and Hibernate, I think you should use the HiberanteTemplate, maybe this tutorial would help you.

网友答案:

it's work now i forget to put

<tx:annotation-driven transaction-manager="transactionManager"/>

and i put

sessionFactory.getCurrentSession();

it seem to work after tx:annotation-driven sessionFactory.openSession() doesn't open the right session i think.

but can anyone explain me why ?

相关阅读:
Top