Spring MVC+Hibernate、JavaConfig
WebAppConfig:
package com.sprhib.init;
import java.util.Properties;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
@Configuration
@ComponentScan("com.sprhib")
@EnableWebMvc
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
public class WebAppConfig {
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
@Resource
private Environment env;
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
sessionFactoryBean.setHibernateProperties(hibProperties());
return sessionFactoryBean;
}
private Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
return properties;
}
@Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
@Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
用户
package com.sprhib.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Timestamp;
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue
private Integer id;
private String name;
private Integer age;
private Boolean isAdmin;
private Timestamp createdDate;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Boolean getAdmin() {
return isAdmin;
}
public void setAdmin(Boolean admin) {
isAdmin = admin;
}
public Timestamp getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Timestamp createdDate) {
this.createdDate = createdDate;
}
}
package com.sprhib.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.sprhib.model.User;
@Repository
public class UserDAOImpl implements UserDAO {
@Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
public void addUser(User user) {
getCurrentSession().save(user);
}
public void updateUser(User user) {
User userUpdate = getUser(user.getId());
userUpdate.setName(user.getName());
userUpdate.setAge(user.getAge());
userUpdate.setAdmin(user.getAdmin());
userUpdate.setCreatedDate(user.getCreatedDate());
getCurrentSession().update(userUpdate);
}
public User getUser(int id) {
return (User)getCurrentSession().get(User.class,id);
}
public void deleteUser(int id) {
User user = getUser(id);
if (user!=null)
getCurrentSession().delete(user);
}
public List<User> getUsers() {
System.out.println("zzz");
return getCurrentSession().createQuery("FROM User").list();
}
}
package com.sprhib.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.sprhib.model.User;
@Repository
public class UserDAOImpl implements UserDAO {
@Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
public void addUser(User user) {
getCurrentSession().save(user);
}
public void updateUser(User user) {
User userUpdate = getUser(user.getId());
userUpdate.setName(user.getName());
userUpdate.setAge(user.getAge());
userUpdate.setAdmin(user.getAdmin());
userUpdate.setCreatedDate(user.getCreatedDate());
getCurrentSession().update(userUpdate);
}
public User getUser(int id) {
return (User)getCurrentSession().get(User.class,id);
}
public void deleteUser(int id) {
User user = getUser(id);
if (user!=null)
getCurrentSession().delete(user);
}
public List<User> getUsers() {
return getCurrentSession().createQuery("FROM User").list();
}
}
package com.sprhib.controller;
import java.util.List;
import com.sprhib.model.User;
import com.sprhib.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping(value="/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value="/add", method=RequestMethod.GET)
public ModelAndView addUserPage()
{
ModelAndView modelAndView = new ModelAndView("add-user-form");
modelAndView.addObject("user",new User());
return modelAndView;
}
@RequestMapping(value="/add", method=RequestMethod.POST)
public ModelAndView addingUser(@ModelAttribute User user) {
ModelAndView modelAndView = new ModelAndView("home");
userService.addUser(user);
String message = "User was successfully added.";
modelAndView.addObject("message", message);
return modelAndView;
}
@RequestMapping(value="/list")
public ModelAndView listOfUsers() {
ModelAndView modelAndView = new ModelAndView("list-of-users");
List<User> users = userService.getUsers();
modelAndView.addObject("users", users);
return modelAndView;
}
@RequestMapping(value="/edit/{id}", method=RequestMethod.GET)
public ModelAndView editUserPage(@PathVariable Integer id) {
ModelAndView modelAndView = new ModelAndView("edit-user-form");
User user = userService.getUser(id);
modelAndView.addObject("user",user);
return modelAndView;
}
@RequestMapping(value="/edit/{id}", method=RequestMethod.POST)
public ModelAndView edditingUser(@ModelAttribute User user, @PathVariable Integer id) {
ModelAndView modelAndView = new ModelAndView("home");
userService.updateUser(user);
String message = "User was successfully updated.";
modelAndView.addObject("message", message);
return modelAndView;
}
@RequestMapping(value="/delete/{id}", method=RequestMethod.GET)
public ModelAndView deleteUser(@PathVariable Integer id) {
ModelAndView modelAndView = new ModelAndView("home");
userService.deleteUser(id);
String message = "User was successfully deleted.";
modelAndView.addObject("message", message);
return modelAndView;
}
}
#DB properties:
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/test
db.username=root
db.password=root
#Hibernate Configuration:
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.show_sql=true
entitymanager.packages.to.scan=com.sprhib.model
HTTP状态500-请求处理失败;嵌套异常为org.springframework.transaction.CanNotCreateTransactionException:无法打开事务的Hibernate会话;嵌套异常为java.lang.NoClassDefoundError:org/hibernate/engine/transaction/spi/transactioncontext
类型异常报告
消息请求处理失败;嵌套异常为org.springframework.transaction.CanNotCreateTransactionException:无法打开事务的Hibernate会话;嵌套异常为java.lang.NoClassDefoundError:org/hibernate/engine/transaction/spi/transactioncontext
根本原因
根本原因
根本原因
对于Hibernate4,可以使用org.springframework.orm.hibernate4.hibernateTransactionManager
。该类使用Hibernate4中的TransactionContext
。
看起来你用的是Hibernate5。换一下就行了
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
对此
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
有关您编写的代码问题的问题必须描述特定问题-并且在问题本身中包含有效代码以重现它。有关指导,请参阅SSCCE. org。 在我的应用程序中,我有一个模块,用于在数据库中搜索用户并在jsp内的表中显示他们的信息。我只是在应用程序中设置了Spring Security性。我能够从登录页面连接到数据库,尽管出于某种原因,DAO的CRUD操作(在本例中是搜索)都不起作用。 谢谢,如果我能提供更多信息,请告
我有一个运行完整的Spring MVC应用程序,运行Spring Security,但每当服务器有一段时间不活动,有人试图登录时,我就会出现以下错误: HTTP状态500-请求处理失败;嵌套的异常是org。springframework。交易CannotCreateTransactionException:无法为事务打开Hibernate会话;嵌套的异常是org。冬眠TransactionExce
错误日志: 冬眠图。JAVA 测试类CategoryTestCase。JAVA 为什么我无法为事务打开Hibernate会话;嵌套异常,似乎一切都很好,为什么我得到这个错误你也可以检查git Hub代码它的相同问题,请帮助我解决这个问题https://github.com/rustyamigo/online-shopping
我不熟悉SpringMVC和Hibernate。尝试使用SpringMVC(4.0.3)、Hibernate(4.3.5)和MySQL作为后端创建一个测试web应用程序。 连接到DB没有问题,因为我尝试使用简单的JDBC连接语句从示例testJavaClass中的同一个DB中获取数据,并且能够获取记录。 错误日志: 这是我的pom。xml: Eclipse中的项目结构: servlet上下文。xm
HibernateConfig CategoryDAOImpl 类别 类别测试类 获取此错误 为什么我得到嵌套异常 无法打开事务的Hibernate会话 似乎一切都很好,为什么会出现这个错误? 您也可以检查github代码
我对Hibernate中的会话和事务的概念有点困惑。据我所知,Hibernate使用会话(持久性上下文),它基本上是需要持久,删除或数据库中任何内容的实体的缓存。会话封装事务,因此我启动一个会话,然后创建一个事务。事务关闭后,持久性上下文中的所有内容都将刷新到数据库,如果我关闭会话,也会发生同样的事情。 为什么我需要两者?我可以在不创建交易的情况下做同样的事情吗?