Spring 4.3.0.RELEASE + Hibernate 5.2.0.Final - 无法为当前线程获取事务同步会话
Spring 4.3.0.RELEASE + Hibernate 5.2.0.Final - Could not obtain transaction-synchronized Session for current thread
嗨,
我收到了这个错误,我不知道为什么?那里的所有定义,但在我尝试将数据插入我的数据库时仍然出现此错误。
"tx:annotation-driven" 在 appconfig-data.xml
我从"UserController"
调用了加法函数
它不起作用的原因可能是什么?
错误日志:
יול 08, 2016 1:06:23 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [searcher] in context with path [/Searcher] threw exception [Request processing failed; nested exception is org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread] with root cause
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate5.SpringSessionContext.currentSession(SpringSessionContext.java:133)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:454)
at com.searcher.dao.EcommerceImp.add(EcommerceImp.java:28)
at com.searcher.controller.UserController.registration(UserController.java:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:112)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169)
at
类
** UserController.java"
package com.searcher.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.searcher.dao.RoleDAO;
import com.searcher.entity.RoleEntity;
import com.searcher.entity.UserEntity;
import com.searcher.service.SecurityService;
import com.searcher.service.UserService;
import com.searcher.validator.UserValidator;
@Controller
public class UserController {
@Autowired
private UserService userService;
@Autowired
private SecurityService securityService;
@Autowired
private UserValidator userValidator;
@Autowired
RoleDAO roleDAO;
@RequestMapping(value = "/registration", method = RequestMethod.GET)
public String registration(Model model) {
model.addAttribute("userForm", new UserEntity());
try {
// Creatinw Role Entity
RoleEntity roleUser = new RoleEntity();
RoleEntity roleAdmin = new RoleEntity();
roleUser.setName("ROLE_USER");
roleAdmin.setName("ROLE_ADMIN");
roleDAO.add(roleUser);
roleDAO.add(roleAdmin);
} catch (Exception e) {
// TODO Auto-generated catch block
throw e;
}
return "registration";
}
@RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(@ModelAttribute("userForm") UserEntity userForm, BindingResult bindingResult, Model model) {
userValidator.validate(userForm, bindingResult);
if (bindingResult.hasErrors()) {
return "registration";
}
userService.add(userForm);
securityService.autologin(userForm.getName(), userForm.getPasswordConfirm());
return "redirect:/welcome";
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model, String error, String logout) {
if (error != null)
model.addAttribute("error", "Your username and password is invalid.");
if (logout != null)
model.addAttribute("message", "You have been logged out successfully.");
return "login";
}
@RequestMapping(value = {"/", "/welcome"}, method = RequestMethod.GET)
public String welcome(Model model) {
return "welcome";
}
}
UserEntity.java
package com.searcher.entity;
import java.util.List;
import java.util.Set;
import javax.persistence.*;
@Entity
@Table(name="user")
public class UserEntity {
@Id
@Column(name="User_Id")
@GeneratedValue
private long Id;
@Column(name="Name")
private String Name;
@Column(name="Password")
private String Password;
@Column(name="Password_Confirm")
private String passwordConfirm;
@Column(name="Phone")
private String Phone;
@Column(name="Email")
private String Email;
@ElementCollection(targetClass=RoleEntity.class)
private Set<RoleEntity> roles;
@ManyToMany
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
public Set<RoleEntity> getRoles() {
return roles;
}
public void setRoles(Set<RoleEntity> roles) {
this.roles = roles;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
public long getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
@Override
public String toString(){
return "Id = " + Id + ", Name = " + Name + ", Password = " + Password + ", Phone = " + Phone + ", Email = " + Email;
}
}
角色实体
package com.searcher.entity;
import java.util.Set;
import javax.persistence.*;
@Entity
@Table(name = "role")
public class RoleEntity {
@Id
@GeneratedValue
@Column(name="Id")
private Long Id;
@Column(name="Name")
private String Name;
@ElementCollection(targetClass=UserEntity.class)
private Set<UserEntity> users;
public Long getId() {
return Id;
}
public void setId(Long id) {
this.Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
this.Name = name;
}
@ManyToMany(mappedBy = "roles")
public Set<UserEntity> getUsers() {
return users;
}
public void setUsers(Set<UserEntity> users) {
this.users = users;
}
}
DAO
UserDAOImp
package com.searcher.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.searcher.entity.UserEntity;
@Repository
public class UserImp implements UserDAO{
private static final Logger logger = LoggerFactory.getLogger(UserDAO.class);
@Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
@Override
public void add(UserEntity user) {
this.sessionFactory.getCurrentSession().persist(user);
logger.info("UserEntity saved successfully, UserEntity Details="+user);
}
@Override
public void edit(UserEntity user) {
this.sessionFactory.getCurrentSession().update(user);
logger.info("UserEntity updated successfully, UserEntity Details="+user);
}
@Override
public void deleteById(int id) {
UserEntity userToDelete = getUserById(id);
this.sessionFactory.getCurrentSession().delete(userToDelete);
logger.info("UserEntity deleted successfully, UserEntity Details="+userToDelete);
}
@Override
public UserEntity getUserById(int id) {
UserEntity userReturn = (UserEntity)this.sessionFactory.getCurrentSession().get(UserEntity.class, id);
logger.info("UserEntity founded successfully, UserEntity Details="+userReturn);
return userReturn;
}
@Override
public UserEntity getUserByName(String name) {
try{
UserEntity userReturn =
(UserEntity)this.sessionFactory.getCurrentSession().createQuery("from user where Name ='" + name + "'");
if (userReturn != null){
logger.info("UserEntity founded successfully, UserEntity Details="+userReturn);
}
else{
logger.info("UserEntity Not found with Name= "+userReturn);
}
return userReturn;
}catch (Exception ex){
}
return null;
}
@SuppressWarnings({ "unchecked", "deprecation" })
@Override
public List<UserEntity> getAllUser() {
List<UserEntity> userList = this.sessionFactory.getCurrentSession().createQuery("from user").list();
logger.info("List<UserEntity> upload successfully, List<UserEntity> Details="+userList.toString());
return userList;
}
}
角色DAOIMP
package com.searcher.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.searcher.entity.RoleEntity;
@Repository
public class RoleImp implements RoleDAO {
private static final Logger logger = LoggerFactory.getLogger(RoleDAO.class);
@Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
@Override
public void add(RoleEntity role) {
this.sessionFactory.getCurrentSession().persist(role);
logger.info("RoleEntity saved successfully, RoleEntity Details="+role);
}
@Override
public void edit(RoleEntity role) {
this.sessionFactory.getCurrentSession().update(role);
logger.info("RoleEntity updated successfully, RoleEntity Details="+role);
}
@Override
public void deleteById(int id) {
RoleEntity roleToDelete = getRoleById(id);
this.sessionFactory.getCurrentSession().delete(roleToDelete);
logger.info("RoleEntity deleted successfully, RoleEntity Details="+roleToDelete);
}
@Override
public RoleEntity getRoleById(int id) {
RoleEntity roleReturn = (RoleEntity)this.sessionFactory.getCurrentSession().get(RoleEntity.class, id);
logger.info("RoleEntity founded successfully, RoleEntity Details="+roleReturn);
return roleReturn;
}
@Override
public RoleEntity getRoleByName(String name) {
RoleEntity roleReturn =
(RoleEntity)this.sessionFactory.getCurrentSession().createNamedQuery("from role where Name =" + name);
logger.info("RoleEntity founded successfully, RoleEntity Details="+roleReturn);
return roleReturn;
}
@SuppressWarnings({ "unchecked", "deprecation" })
@Override
public List<RoleEntity> getAllRole() {
List<RoleEntity> roleList = this.sessionFactory.getCurrentSession().createQuery("from role").list();
logger.info("List<RoleEntity> upload successfully, List<RoleEntity> Details="+roleList.toString());
return roleList;
}
}
UserServiceImp
package com.searcher.service;
import java.util.HashSet;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.searcher.dao.RoleDAO;
import com.searcher.dao.UserDAO;
import com.searcher.entity.UserEntity;
@Service("userService")
public class UserServiceImp implements UserService{
@Autowired
private UserDAO userDAO;
@Autowired
private RoleDAO roleDAO;
//@Autowired(required=true)
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
public RoleDAO getRoleDAO() {
return roleDAO;
}
public void setRoleDAO(RoleDAO roleDAO) {
this.roleDAO = roleDAO;
}
public BCryptPasswordEncoder getbCryptPasswordEncoder() {
return bCryptPasswordEncoder;
}
public void setbCryptPasswordEncoder(BCryptPasswordEncoder bCryptPasswordEncoder) {
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
@Override
@Transactional
public void add(UserEntity user) {
try {
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
user.setRoles(new HashSet<>(roleDAO.getAllRole()));
this.userDAO.add(user);
} catch (Exception e) {
// TODO: handle exception
}
}
@Override
@Transactional
public void edit(UserEntity user) {
this.userDAO.edit(user);
}
@Override
@Transactional
public void deleteById(int id) {
this.userDAO.deleteById(id);
}
@Override
@Transactional
public UserEntity getUserById(int id) {
return this.userDAO.getUserById(id);
}
@Override
@Transactional
public UserEntity getUserByName(String name) {
return this.userDAO.getUserByName(name);
}
@Override
@Transactional
public List<UserEntity> getAllUser() {
return this.userDAO.getAllUser();
}
}
RoleServiceImpl
package com.searcher.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.searcher.dao.RoleDAO;
import com.searcher.entity.RoleEntity;
public class RoleServiceImp implements RoleService {
@Autowired
private RoleDAO roleDAO;
public RoleDAO getRoleDAO() {
return roleDAO;
}
public void setRoleDAO(RoleDAO roleDAO) {
this.roleDAO = roleDAO;
}
@Override
@Transactional
public void add(RoleEntity role) {
this.roleDAO.add(role);
}
@Override
@Transactional
public void edit(RoleEntity role) {
this.roleDAO.edit(role);
}
@Override
@Transactional
public void deleteById(int id) {
this.roleDAO.deleteById(id);
}
@Override
@Transactional
public RoleEntity getRoleById(int id) {
return this.roleDAO.getRoleById(id);
}
@Override
@Transactional
public RoleEntity getRoleByName(String name) {
return this.roleDAO.getRoleByName(name);
}
@Override
@Transactional
public List<RoleEntity> getAllRole() {
return (List<RoleEntity>)this.roleDAO.getAllRole();
}
}
这是以下配置文件:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>Searcher</display-name>
<!-- Location of Java @Configuration classes that configure the components that makeup this application -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/appconfig-root.xml</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>searcher</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>searcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
-->
<!--
<servlet-mapping>
<servlet-name>searcher</servlet-name>
<url-pattern>/welcome.jsp</url-pattern>
<url-pattern>/welcome.html</url-pattern>
<url-pattern>*.html</url-pattern>
</servlet-mapping>-->
</web-app>
appconfig-root.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<import resource="appconfig-mvc.xml"/>
<import resource="appconfig-data.xml"/>
<import resource="appconfig-security.xml"/>
<!-- Scans within the base package of the application for @Component classes to configure as beans -->
<context:component-scan base-package="com.searcher.*"/>
<!--<context:property-placeholder location="classpath:application.properties"/>-->
</beans>
appconfig-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.1.xsd">
<http auto-config="true">
<intercept-url pattern="/" access="hasRole('ROLE_USER')"/>
<intercept-url pattern="/welcome" access="hasRole('ROLE_USER')"/>
<form-login login-page="/login" default-target-url="/welcome" authentication-failure-url="/login?error" username-parameter="username" password-parameter="password"/>
<logout logout-success-url="/login?logout" />
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="userDetailsServiceImpl">
<password-encoder ref="encoder"></password-encoder>
</authentication-provider>
</authentication-manager>
<beans:bean id="userDetailsServiceImpl" class="com.searcher.service.UserDetailsServiceImpl"></beans:bean>
<beans:bean id="encoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<beans:constructor-arg name="strength" value="11"/>
</beans:bean>
</beans:beans>
appconfig-data.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Configure the data source bean -->
<!-- DataSource -->
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url"
value="jdbc:mysql://localhost:3306/SearcherDB" />
<beans:property name="username" value="root" />
<beans:property name="password" value="root" />
</beans:bean>
<!-- Hibernate 5 SessionFactory Bean definition -->
<beans:bean id="hibernate5AnnotatedSessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>com.searcher.entity.RoleEntity</beans:value>
<beans:value>com.searcher.entity.UserEntity</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
<beans:prop key="hibernate.format_sql">true</beans:prop>
<!-- <beans:prop key="hibernate.hbm2ddl.auto">create</beans:prop> -->
</beans:props>
</beans:property>
</beans:bean>
<!-- User -->
<beans:bean id="userDAO" class="com.searcher.dao.UserImp">
<beans:property name="sessionFactory" ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="userService" class="com.searcher.service.UserServiceImp">
<beans:property name="userDAO" ref="userDAO"></beans:property>
</beans:bean>
<!-- Role -->
<beans:bean id="roleDAO" class="com.searcher.dao.RoleImp">
<beans:property name="sessionFactory" ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Configure the transaction manager bean -->
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
</beans>
appconfig-mvc.xml
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/"/>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:validation</value>
</list>
</property>
</bean>
<!-- Resolves views selected for rendering by @Controllers to .jsp resources
in the /WEB-INF/views directory -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.JstlView</value>
</property>
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
您在 UserController.registration
方法中使用非事务性 daos:
roleDAO.add(roleUser);
roleDAO.add(roleAdmin);
改用RoleServiceImpl
。
嗨, 我收到了这个错误,我不知道为什么?那里的所有定义,但在我尝试将数据插入我的数据库时仍然出现此错误。
"tx:annotation-driven" 在 appconfig-data.xml
我从"UserController"
调用了加法函数
它不起作用的原因可能是什么?
错误日志:
יול 08, 2016 1:06:23 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [searcher] in context with path [/Searcher] threw exception [Request processing failed; nested exception is org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread] with root cause
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate5.SpringSessionContext.currentSession(SpringSessionContext.java:133)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:454)
at com.searcher.dao.EcommerceImp.add(EcommerceImp.java:28)
at com.searcher.controller.UserController.registration(UserController.java:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:112)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169)
at
类
** UserController.java"
package com.searcher.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.searcher.dao.RoleDAO;
import com.searcher.entity.RoleEntity;
import com.searcher.entity.UserEntity;
import com.searcher.service.SecurityService;
import com.searcher.service.UserService;
import com.searcher.validator.UserValidator;
@Controller
public class UserController {
@Autowired
private UserService userService;
@Autowired
private SecurityService securityService;
@Autowired
private UserValidator userValidator;
@Autowired
RoleDAO roleDAO;
@RequestMapping(value = "/registration", method = RequestMethod.GET)
public String registration(Model model) {
model.addAttribute("userForm", new UserEntity());
try {
// Creatinw Role Entity
RoleEntity roleUser = new RoleEntity();
RoleEntity roleAdmin = new RoleEntity();
roleUser.setName("ROLE_USER");
roleAdmin.setName("ROLE_ADMIN");
roleDAO.add(roleUser);
roleDAO.add(roleAdmin);
} catch (Exception e) {
// TODO Auto-generated catch block
throw e;
}
return "registration";
}
@RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(@ModelAttribute("userForm") UserEntity userForm, BindingResult bindingResult, Model model) {
userValidator.validate(userForm, bindingResult);
if (bindingResult.hasErrors()) {
return "registration";
}
userService.add(userForm);
securityService.autologin(userForm.getName(), userForm.getPasswordConfirm());
return "redirect:/welcome";
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model, String error, String logout) {
if (error != null)
model.addAttribute("error", "Your username and password is invalid.");
if (logout != null)
model.addAttribute("message", "You have been logged out successfully.");
return "login";
}
@RequestMapping(value = {"/", "/welcome"}, method = RequestMethod.GET)
public String welcome(Model model) {
return "welcome";
}
}
UserEntity.java
package com.searcher.entity;
import java.util.List;
import java.util.Set;
import javax.persistence.*;
@Entity
@Table(name="user")
public class UserEntity {
@Id
@Column(name="User_Id")
@GeneratedValue
private long Id;
@Column(name="Name")
private String Name;
@Column(name="Password")
private String Password;
@Column(name="Password_Confirm")
private String passwordConfirm;
@Column(name="Phone")
private String Phone;
@Column(name="Email")
private String Email;
@ElementCollection(targetClass=RoleEntity.class)
private Set<RoleEntity> roles;
@ManyToMany
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
public Set<RoleEntity> getRoles() {
return roles;
}
public void setRoles(Set<RoleEntity> roles) {
this.roles = roles;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
public long getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
@Override
public String toString(){
return "Id = " + Id + ", Name = " + Name + ", Password = " + Password + ", Phone = " + Phone + ", Email = " + Email;
}
}
角色实体
package com.searcher.entity;
import java.util.Set;
import javax.persistence.*;
@Entity
@Table(name = "role")
public class RoleEntity {
@Id
@GeneratedValue
@Column(name="Id")
private Long Id;
@Column(name="Name")
private String Name;
@ElementCollection(targetClass=UserEntity.class)
private Set<UserEntity> users;
public Long getId() {
return Id;
}
public void setId(Long id) {
this.Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
this.Name = name;
}
@ManyToMany(mappedBy = "roles")
public Set<UserEntity> getUsers() {
return users;
}
public void setUsers(Set<UserEntity> users) {
this.users = users;
}
}
DAO
UserDAOImp
package com.searcher.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.searcher.entity.UserEntity;
@Repository
public class UserImp implements UserDAO{
private static final Logger logger = LoggerFactory.getLogger(UserDAO.class);
@Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
@Override
public void add(UserEntity user) {
this.sessionFactory.getCurrentSession().persist(user);
logger.info("UserEntity saved successfully, UserEntity Details="+user);
}
@Override
public void edit(UserEntity user) {
this.sessionFactory.getCurrentSession().update(user);
logger.info("UserEntity updated successfully, UserEntity Details="+user);
}
@Override
public void deleteById(int id) {
UserEntity userToDelete = getUserById(id);
this.sessionFactory.getCurrentSession().delete(userToDelete);
logger.info("UserEntity deleted successfully, UserEntity Details="+userToDelete);
}
@Override
public UserEntity getUserById(int id) {
UserEntity userReturn = (UserEntity)this.sessionFactory.getCurrentSession().get(UserEntity.class, id);
logger.info("UserEntity founded successfully, UserEntity Details="+userReturn);
return userReturn;
}
@Override
public UserEntity getUserByName(String name) {
try{
UserEntity userReturn =
(UserEntity)this.sessionFactory.getCurrentSession().createQuery("from user where Name ='" + name + "'");
if (userReturn != null){
logger.info("UserEntity founded successfully, UserEntity Details="+userReturn);
}
else{
logger.info("UserEntity Not found with Name= "+userReturn);
}
return userReturn;
}catch (Exception ex){
}
return null;
}
@SuppressWarnings({ "unchecked", "deprecation" })
@Override
public List<UserEntity> getAllUser() {
List<UserEntity> userList = this.sessionFactory.getCurrentSession().createQuery("from user").list();
logger.info("List<UserEntity> upload successfully, List<UserEntity> Details="+userList.toString());
return userList;
}
}
角色DAOIMP
package com.searcher.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.searcher.entity.RoleEntity;
@Repository
public class RoleImp implements RoleDAO {
private static final Logger logger = LoggerFactory.getLogger(RoleDAO.class);
@Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
@Override
public void add(RoleEntity role) {
this.sessionFactory.getCurrentSession().persist(role);
logger.info("RoleEntity saved successfully, RoleEntity Details="+role);
}
@Override
public void edit(RoleEntity role) {
this.sessionFactory.getCurrentSession().update(role);
logger.info("RoleEntity updated successfully, RoleEntity Details="+role);
}
@Override
public void deleteById(int id) {
RoleEntity roleToDelete = getRoleById(id);
this.sessionFactory.getCurrentSession().delete(roleToDelete);
logger.info("RoleEntity deleted successfully, RoleEntity Details="+roleToDelete);
}
@Override
public RoleEntity getRoleById(int id) {
RoleEntity roleReturn = (RoleEntity)this.sessionFactory.getCurrentSession().get(RoleEntity.class, id);
logger.info("RoleEntity founded successfully, RoleEntity Details="+roleReturn);
return roleReturn;
}
@Override
public RoleEntity getRoleByName(String name) {
RoleEntity roleReturn =
(RoleEntity)this.sessionFactory.getCurrentSession().createNamedQuery("from role where Name =" + name);
logger.info("RoleEntity founded successfully, RoleEntity Details="+roleReturn);
return roleReturn;
}
@SuppressWarnings({ "unchecked", "deprecation" })
@Override
public List<RoleEntity> getAllRole() {
List<RoleEntity> roleList = this.sessionFactory.getCurrentSession().createQuery("from role").list();
logger.info("List<RoleEntity> upload successfully, List<RoleEntity> Details="+roleList.toString());
return roleList;
}
}
UserServiceImp
package com.searcher.service;
import java.util.HashSet;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.searcher.dao.RoleDAO;
import com.searcher.dao.UserDAO;
import com.searcher.entity.UserEntity;
@Service("userService")
public class UserServiceImp implements UserService{
@Autowired
private UserDAO userDAO;
@Autowired
private RoleDAO roleDAO;
//@Autowired(required=true)
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
public RoleDAO getRoleDAO() {
return roleDAO;
}
public void setRoleDAO(RoleDAO roleDAO) {
this.roleDAO = roleDAO;
}
public BCryptPasswordEncoder getbCryptPasswordEncoder() {
return bCryptPasswordEncoder;
}
public void setbCryptPasswordEncoder(BCryptPasswordEncoder bCryptPasswordEncoder) {
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
@Override
@Transactional
public void add(UserEntity user) {
try {
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
user.setRoles(new HashSet<>(roleDAO.getAllRole()));
this.userDAO.add(user);
} catch (Exception e) {
// TODO: handle exception
}
}
@Override
@Transactional
public void edit(UserEntity user) {
this.userDAO.edit(user);
}
@Override
@Transactional
public void deleteById(int id) {
this.userDAO.deleteById(id);
}
@Override
@Transactional
public UserEntity getUserById(int id) {
return this.userDAO.getUserById(id);
}
@Override
@Transactional
public UserEntity getUserByName(String name) {
return this.userDAO.getUserByName(name);
}
@Override
@Transactional
public List<UserEntity> getAllUser() {
return this.userDAO.getAllUser();
}
}
RoleServiceImpl
package com.searcher.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.searcher.dao.RoleDAO;
import com.searcher.entity.RoleEntity;
public class RoleServiceImp implements RoleService {
@Autowired
private RoleDAO roleDAO;
public RoleDAO getRoleDAO() {
return roleDAO;
}
public void setRoleDAO(RoleDAO roleDAO) {
this.roleDAO = roleDAO;
}
@Override
@Transactional
public void add(RoleEntity role) {
this.roleDAO.add(role);
}
@Override
@Transactional
public void edit(RoleEntity role) {
this.roleDAO.edit(role);
}
@Override
@Transactional
public void deleteById(int id) {
this.roleDAO.deleteById(id);
}
@Override
@Transactional
public RoleEntity getRoleById(int id) {
return this.roleDAO.getRoleById(id);
}
@Override
@Transactional
public RoleEntity getRoleByName(String name) {
return this.roleDAO.getRoleByName(name);
}
@Override
@Transactional
public List<RoleEntity> getAllRole() {
return (List<RoleEntity>)this.roleDAO.getAllRole();
}
}
这是以下配置文件:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>Searcher</display-name>
<!-- Location of Java @Configuration classes that configure the components that makeup this application -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/appconfig-root.xml</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>searcher</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>searcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
-->
<!--
<servlet-mapping>
<servlet-name>searcher</servlet-name>
<url-pattern>/welcome.jsp</url-pattern>
<url-pattern>/welcome.html</url-pattern>
<url-pattern>*.html</url-pattern>
</servlet-mapping>-->
</web-app>
appconfig-root.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<import resource="appconfig-mvc.xml"/>
<import resource="appconfig-data.xml"/>
<import resource="appconfig-security.xml"/>
<!-- Scans within the base package of the application for @Component classes to configure as beans -->
<context:component-scan base-package="com.searcher.*"/>
<!--<context:property-placeholder location="classpath:application.properties"/>-->
</beans>
appconfig-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.1.xsd">
<http auto-config="true">
<intercept-url pattern="/" access="hasRole('ROLE_USER')"/>
<intercept-url pattern="/welcome" access="hasRole('ROLE_USER')"/>
<form-login login-page="/login" default-target-url="/welcome" authentication-failure-url="/login?error" username-parameter="username" password-parameter="password"/>
<logout logout-success-url="/login?logout" />
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="userDetailsServiceImpl">
<password-encoder ref="encoder"></password-encoder>
</authentication-provider>
</authentication-manager>
<beans:bean id="userDetailsServiceImpl" class="com.searcher.service.UserDetailsServiceImpl"></beans:bean>
<beans:bean id="encoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<beans:constructor-arg name="strength" value="11"/>
</beans:bean>
</beans:beans>
appconfig-data.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Configure the data source bean -->
<!-- DataSource -->
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url"
value="jdbc:mysql://localhost:3306/SearcherDB" />
<beans:property name="username" value="root" />
<beans:property name="password" value="root" />
</beans:bean>
<!-- Hibernate 5 SessionFactory Bean definition -->
<beans:bean id="hibernate5AnnotatedSessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>com.searcher.entity.RoleEntity</beans:value>
<beans:value>com.searcher.entity.UserEntity</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
<beans:prop key="hibernate.format_sql">true</beans:prop>
<!-- <beans:prop key="hibernate.hbm2ddl.auto">create</beans:prop> -->
</beans:props>
</beans:property>
</beans:bean>
<!-- User -->
<beans:bean id="userDAO" class="com.searcher.dao.UserImp">
<beans:property name="sessionFactory" ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="userService" class="com.searcher.service.UserServiceImp">
<beans:property name="userDAO" ref="userDAO"></beans:property>
</beans:bean>
<!-- Role -->
<beans:bean id="roleDAO" class="com.searcher.dao.RoleImp">
<beans:property name="sessionFactory" ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Configure the transaction manager bean -->
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
</beans>
appconfig-mvc.xml
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/"/>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:validation</value>
</list>
</property>
</bean>
<!-- Resolves views selected for rendering by @Controllers to .jsp resources
in the /WEB-INF/views directory -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.JstlView</value>
</property>
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
您在 UserController.registration
方法中使用非事务性 daos:
roleDAO.add(roleUser);
roleDAO.add(roleAdmin);
改用RoleServiceImpl
。