SpringMVC4+Hibernate5+SQLServer 2014 整合(包括增删改查分页)
前言
前面整合完了SpringMVC+MyBatis,自然也少不了SpringMVC+Hibernate,严格来说Hibernate才是我们真正想要的ORM框架么。只记得最初学习hibernate时,又是config.xml又是hml.xml,各种的xml。 今天试着用SpringMVC4整合Hibernate5,使用自动扫描注解的方式处理hibernate类文件,几乎零配置,这就爽很多了是不是。
开发环境
SpringMVC4、Hibernate5、SQLServer2014
项目结构
SpringMVC+Hibernate整合
1、查询分页数据
从控制台里看hql执行情况
2、pom.xml,先把依赖的jar准备好
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 3 <modelVersion>4.0.0modelVersion> 4 <groupId>com.autohomegroupId> 5 <artifactId>SpringMVC6artifactId> 6 <packaging>warpackaging> 7 <version>1.0-SNAPSHOTversion> 8 <name>SpringMVC6name> 9 <url>http://maven.apache.orgurl> 10 <dependencies> 11 <dependency> 12 <groupId>org.springframeworkgroupId> 13 <artifactId>spring-beansartifactId> 14 <version>4.3.6.RELEASEversion> 15 dependency> 16 <dependency> 17 <groupId>org.springframeworkgroupId> 18 <artifactId>spring-contextartifactId> 19 <version>4.3.6.RELEASEversion> 20 dependency> 21 <dependency> 22 <groupId>org.springframeworkgroupId> 23 <artifactId>spring-coreartifactId> 24 <version>4.3.6.RELEASEversion> 25 dependency> 26 <dependency> 27 <groupId>org.springframeworkgroupId> 28 <artifactId>spring-testartifactId> 29 <version>4.3.6.RELEASEversion> 30 dependency> 31 <dependency> 32 <groupId>org.springframeworkgroupId> 33 <artifactId>spring-webartifactId> 34 <version>4.3.6.RELEASEversion> 35 dependency> 36 <dependency> 37 <groupId>org.springframeworkgroupId> 38 <artifactId>spring-webmvcartifactId> 39 <version>4.3.6.RELEASEversion> 40 dependency> 41 <dependency> 42 <groupId>org.springframeworkgroupId> 43 <artifactId>spring-jdbcartifactId> 44 <version>4.3.6.RELEASEversion> 45 dependency> 46 <dependency> 47 <groupId>org.springframeworkgroupId> 48 <artifactId>spring-ormartifactId> 49 <version>4.3.6.RELEASEversion> 50 dependency> 51 <dependency> 52 <groupId>junitgroupId> 53 <artifactId>junitartifactId> 54 <version>4.10version> 55 dependency> 56 57 <dependency> 58 <groupId>javax.servletgroupId> 59 <artifactId>javax.servlet-apiartifactId> 60 <version>3.1.0version> 61 dependency> 62 63 <dependency> 64 <groupId>org.hibernategroupId> 65 <artifactId>hibernate-coreartifactId> 66 <version>5.2.9.Finalversion> 67 dependency> 68 <dependency> 69 <groupId>com.microsoft.sqlservergroupId> 70 <artifactId>sqljdbc4artifactId> 71 <version>4.0version> 72 dependency> 73 74 <dependency> 75 <groupId>jstlgroupId> 76 <artifactId>jstlartifactId> 77 <version>1.2version> 78 dependency> 79 80 <dependency> 81 <groupId>taglibsgroupId> 82 <artifactId>standardartifactId> 83 <version>1.1.2version> 84 dependency> 85 86 dependencies> 87 <build> 88 <finalName>SpringMVC6finalName> 89 build> 90 project>
3、web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>Archetype Created Web Applicationdisplay-name> <context-param> <param-name>contextConfigLocationparam-name> <param-value>classpath:applicationContext.xmlparam-value> context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class> listener> <servlet> <servlet-name>SpringMVCservlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class> <init-param> <param-name>contextConfigLocationparam-name> <param-value>classpath:springmvc-servlet.xmlparam-value> init-param> servlet> <servlet-mapping> <servlet-name>SpringMVCservlet-name> <url-pattern>/url-pattern> servlet-mapping> web-app>
4、springmvc-servlet.xml。这里整合主要配置jdbc数据源、hibernate sessionfactory、事务管理器
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations" value="classpath:config/jdbc.properties"/> <property name="fileEncoding" value="UTF-8"/> bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${sqlserver.driver}"/> <property name="url" value="${sqlserver.url}"/> <property name="username" value="${sqlserver.username}"/> <property name="password" value="${sqlserver.password}"/> bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialectprop> <prop key="hibernate.show_sql">trueprop> <prop key="hibernate.format_sql">trueprop> props> property> <property name="packagesToScan"> <list> <value>com.autohome.modelvalue> list> property> bean> <bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> bean> <mvc:annotation-driven/> <mvc:default-servlet-handler/> <context:component-scan base-package="com.autohome.controller"/> <context:component-scan base-package="com.autohome.service"/> <context:component-scan base-package="com.autohome.dao"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> bean> beans>
5、UserInfoDao
package com.autohome.dao; import com.autohome.model.UserInfo; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.query.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.hibernate.Transaction; import java.util.List; @Repository public class UserInfoDao { @Autowired private SessionFactory sessionFactory; public ListlistAllUser(){ String hql="from UserInfo"; Session session = sessionFactory.openSession(); Query query = session.createQuery(hql); List list = query.list(); return list; } public List getAllUser(){ Session session = sessionFactory.openSession(); String sql="select * from t_userinfo"; //执行原生sql查询语句 Query query = session.createSQLQuery(sql); List list=query.list(); //执行原生增加、删除、修改语句 //query.executeUpdate(); return list; } public List listPageUser(int offset,int rows){ String hql="from UserInfo"; Session session = sessionFactory.openSession(); Query query = session.createQuery(hql); query.setFirstResult(offset); query.setMaxResults(rows); List list = query.list(); return list; } public void save(UserInfo model){ Session session = sessionFactory.openSession(); Transaction tran=session.getTransaction(); tran.begin(); session.save(model); tran.commit(); } public void delete(Integer id){ String hql="delete from UserInfo where id=?"; Session session = sessionFactory.openSession(); Transaction tran=session.getTransaction(); tran.begin(); Query query = session.createQuery(hql); query.setParameter(0,id); query.executeUpdate(); tran.commit(); } public void update(UserInfo model){ Session session = sessionFactory.openSession(); Transaction tran=session.getTransaction(); tran.begin(); session.update(model); tran.commit(); } }
6、UserInfoService
package com.autohome.service; import com.autohome.dao.UserInfoDao; import com.autohome.model.UserInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserInfoBiz { @Autowired UserInfoDao userInfoDao; public ListlistAllUser(){ return userInfoDao.listAllUser(); } public List getAllUser(){ return userInfoDao.getAllUser(); } public List listPageUser(int offset,int rows){ return userInfoDao.listPageUser(offset,rows); } public void save(UserInfo model){ userInfoDao.save(model); } public void update(UserInfo model){ userInfoDao.update(model); } public void delete(Integer id){ userInfoDao.delete(id); } }
7、UserController
package com.autohome.controller; import com.autohome.model.UserInfo; import com.autohome.service.UserInfoBiz; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import java.util.List; @Controller @RequestMapping("/User") public class UserController { @Autowired UserInfoBiz userInfoBiz; @RequestMapping("/index") public ModelAndView index(int pageIndex,int pageSize){ // UserInfo model=new UserInfo(); // model.setName("zhangsan"); // model.setAddress("USA2017-03-28"); // // userInfoBiz.save(model); // UserInfo model=new UserInfo(); // model.setId(1); // model.setName("李四"); // model.setAddress("USA2017-03-28"); // userInfoBiz.update(model); // userInfoBiz.delete(51); Listlist = userInfoBiz.listPageUser((pageIndex-1)*pageSize,pageSize); List users = userInfoBiz.getAllUser(); System.out.println("size:"+users.size()); ModelAndView mav =new ModelAndView("index"); mav.addObject("list",list); mav.addObject("title","用户列表"); return mav; } }
8、UserInfo POJO
package com.autohome.model; import javax.persistence.*; import java.io.Serializable; @Entity @Table(name="t_userinfo") public class UserInfo implements Serializable { @Id @Column(name="id") @GeneratedValue(strategy =GenerationType.IDENTITY) private Integer id; @Column(name="name") private String name; @Column(name="address") private String address; 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 String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
总结
在做这个整合demo的时候遇到两个问题,第一是实现分页调用querysetFirstResult和setMaxResults一直报一个索引超出。后更改hibernate断言SQLServer2008Dialect,一开始我用的是SQLServerDialect,因为本地连接sql server2014。第二是在jsp中用jstl显示controller中传过来的值时jsp中无法显示,百度了下是mavel默认生成web.xml的命名空间导致的(查看上面贴的web.xml代码)
另外记得以前学习hibernate类文件全部是用hml.xml来写,现在则是直接扫描model包内的所有实体,实体使用Entity、Table、ID、Column注解,sql server id自增用注解GeneratedValue(strategy =GenerationType.IDENTITY),也确实从项目开发效果和代码整洁程度有很大提高。
参考
http://blog.csdn.net/xumengxing/article/details/8728255
https://my.oschina.net/zimingforever/blog/216909