HibernateException:无法获取当前线程3的事务同步会话

时间:2014-10-31 13:37:49

标签: spring hibernate spring-mvc

我收到错误:

org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread

如果我在DataSourceContext.xml中添加以下代码段,我没有收到任何错误,应用程序按预期工作。

<bean id="userDAO" class="com.my.portal.user.UserDAOImpl">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>

我希望我的扫描包和注册bean在DataSourceContext.xml中没有上面的代码片段。

我怎样才能做到这一点?

以下是我的完整代码:

Web.xml中

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/*.xml</param-value>
</context-param>

<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- Processes application requests -->
<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/spring/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

DataSourceContext.xml

<!-- Data Source Setup -->
<bean id="myDS" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
    <property name="username" value="root"/>
    <property name="password" value=""/>
    <property name="maxIdle" value="5"/>
    <property name="maxActive" value="10"/>
</bean>

<!-- Hibernate Sessionfactory Bean Definition -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="myDS"/>
    <property name="annotatedClasses">
        <list>
            <value>com.my.portal.user.User</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>

<!-- Hibernate Transaction Setup -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>

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

User.java

@Entity
@Table(name="USER")  
public class User {

    @Id
    @Column(name="UserId")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int UserId;
    private String FirstName;
    private String LastName;
    public int getUserId() {
        return UserId;
    }
    public void setUserId(int userId) {
        UserId = userId;
    }
    public String getFirstName() {
        return FirstName;
    }
    public void setFirstName(String firstName) {
        FirstName = firstName;
    }
    public String getLastName() {
        return LastName;
    }
    public void setLastName(String lastName) {
        LastName = lastName;
    }
    @Override
    public String toString(){
        return "UserId="+UserId+", FirstName="+FirstName+", LastName="+LastName;
    }
}

UserController.java

@Controller
public class UserController {

private static final Logger logger = LoggerFactory.getLogger(UserController.class);

private UserService userService;

@Autowired
public UserController(UserService userService){
    this.userService = userService;
}

@RequestMapping(value = "/user", method = RequestMethod.GET)
public String user(Locale locale, Model model){
    model.addAttribute("getUser",userService.getUser());
    return "user";

}

UserDAO.java

@Repository
public interface UserDAO {

    public List<User> getUser();

}

UserDAOImpl.java

@Repository
@Transactional
public class UserDAOImpl  implements UserDAO {

    private static final Logger logger = LoggerFactory.getLogger(UserDAOImpl.class);

    private SessionFactory sessionFactory;

    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory){
        this.sessionFactory = sessionFactory;
    }

    private Session currentSession() {
        return sessionFactory.getCurrentSession();
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<User> getUser() {
        List<User> userList = currentSession().createQuery("from User").list();
        return userList;
    }

}

userService.java

@Service
public interface UserService {

    public String getMessage();
}

UserServiceImpl.java

@Service
public class UserServiceImpl implements UserService {

    private UserDAO userDAO;

    @Autowired
    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public String getMessage(){
        return "User Registration Page";
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<User> getUser(){
        logger.info("getUser()");
        return this.userDAO.getUser();
    }
}

0 个答案:

没有答案