如何正确配置tx:annotation-driven?

时间:2016-03-24 16:11:36

标签: hibernate spring-mvc java-ee

我是使用SpringMVC的JavaEE的新手,我正在开发一个简单的JavaEE项目(Spring + Hibernate),但我仍然坚持配置一些东西。我试图搜索如何解决,但我找不到合适的解决方案。

这是我的dispatcher-servlet.xml

 ...
<context:component-scan base-package="com.springmvcpattern.controller"/>
<context:component-scan base-package="com.springmvcpattern.dao"/>
<context:component-scan base-package="com.springmvcpattern.dao.impl"/>
<context:component-scan base-package="com.springmvcpattern.service"/>
<context:component-scan base-package="com.springmvcpattern.service.impl"/>


<bean id="viewResolver"          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:prefix="/WEB-INF/jsp/"
      p:suffix=".jsp" />

 <bean id="propertyConfigurer"
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
      p:location="/WEB-INF/resources/database/jdbc.properties" />

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    p:driverClassName="${jdbc.driverClassName}"
    p:url="${jdbc.url}"
    p:username="${jdbc.username}"
    p:password="${jdbc.password}">
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation">
        <value>classpath:hibernate.cfg.xml</value>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean> 

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

<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="dataSource" ref="dataSource" />
    <property name="sessionFactory" ref="sessionFactory" />
</bean>
....

我的hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
      <session-factory>
          <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
          <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
          <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/springhib?zeroDateTimeBehavior=convertToNull</property>
          <property name="hibernate.connection.username">root</property>
          <property name="hibernate.connection.password">root</property>
          <property name="hibernate.current_session_context_class">thread</property>
          <mapping class="com.springmvcpattern.model.Student"/>

    </session-factory>
  </hibernate-configuration>

我的DAO

@Repository("studentDao")
public class StudentDaoImpl implements StudentDao{

@Autowired
private SessionFactory session;

@Override
public List<Student> getAllStudents() {
    return session.getCurrentSession().createCriteria(Student.class).list();
}

@Override
public void create(Student student) {
    try {
        session.getCurrentSession().persist(student);        
    } catch (Exception e) {
        throw e;
    }
}

@Override
public Student find(String studentId) {
    return (Student) session.getCurrentSession().createCriteria(Student.class).add(Restrictions.eq("studentId", Integer.parseInt(studentId)));
}

@Override
public void update(Student student) {
    try{
        session.getCurrentSession().merge(student);
    }catch(Exception e){
        throw e;
    }   
}

@Override
public void delete(Student student) {
    try{
        session.getCurrentSession().delete(student);
    }catch(Exception e){
        throw e;
    }
}
}

我的服务

@Service("studentService")
@Transactional
public class StudentServiceImpl implements StudentService{

    @Autowired
    private StudentDao stDao;

    @Override
    public List<Student> getAllStudents() {
     return stDao.getAllStudents();
    }
    @Override
    public void create(Student student) {
     stDao.create(student);
    }
    @Override
    public Student find(String studentId) {
       return stDao.find(studentId);
    }
    @Override
    public void update(Student student) {
       stDao.update(student);
    }
    @Override
    public void delete(Student student) {
       stDao.delete(student);
    }

}

我的控制器

@Controller
@RequestMapping("/students")
public class StudentController {

    @Autowired
    private StudentService stService;

    @RequestMapping(method = RequestMethod.GET)
    public String getAllStudents(Model model){
        model.addAttribute("hello", "Hello World");
        model.addAttribute("students",stService.getAllStudents());
        return "students";
    }
}

当我尝试运行应用程序并单击页面上的列表链接(指向学生页面)时,服务器说:

 25-Mar-2016 00:00:26.404 SEVERE [http-apr-8080-exec-113] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [dispatcher] in context with path [/springmvcpattern] threw exception [Request processing failed; nested exception is   org.hibernate.HibernateException: createCriteria is not valid without active transaction] with root cause
      org.hibernate.HibernateException: createCriteria is not valid without active transaction

如果我在hibernate.cfg.xml中删除了 hibernate.current_session_context_class 服务器说:

25-Mar-2016 09:03:37.581 SEVERE [http-apr-8080-exec-96] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [dispatcher] in context with path [/springmvcpattern] threw exception [Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread] with root cause
 org.hibernate.HibernateException: No Session found for current thread

感谢您的帮助。

P.S。我正在使用Netbeans 8.0.2,Spring4.0.1和Hibernate4.3

0 个答案:

没有答案