SSH(SPRINGMVC)
2015-07-31 23:55
525 查看
前面两篇文章,分别介绍了Springmvc和Spring的搭建方法,本文再搭建hibernate,并建立SSH最基本的代码结构。
Hibernate和前面两个比就比较复杂了,Hibernate是一个orm的框架,也就是负责面向对象中的对象(Object)和关系型数据库 这个关系(Relation)之间的映射(Mapping)。因为关系型数据库的思维方式,和编程的时候对于对象的理解是有偏差的,所以也有一些面向对象 的数据库,但是随着这些orm框架的完善,面向对象的数据库就销声匿迹了。
当然,我这篇文章也只是搭建环境,并不多讲annotation,这个会专门写一篇来讲。
闲话少说,第一步是安装好数据库,我用的是mysql,安装在本地,本开启了mysql服务。之后看程序怎么改进。
1. pom.xml
第一步加入hibernate的相关jar包,首先在properties标签下面定义一个版本:
然后加入hibernate的核心包,因为要让Spring管理一些对象,还要引入spring-orm的包:
除此之外,因为我们要用mysql数据库,并使用c3p0连接池,因此需要引入这两个对应的包:
2. web.xml
hibernate有两种使用方法,一种是通过一个SessionFactory来获取Session,还有一种是通过 EntityManagerFactory来获取entityManager,我忘了什么原因了,刚开始用的EntityManager后来换回了 SessionFactory(hibernate3以前用的是SessionFactory),我后面的描述也都是基于sessionFactory 了。而不管是Session还是EntityManager,我们都要去创建和管理这个对象,当然,有了Spring,这个事情就不用我们来操心了,只需
要在Spring的配置文件里面配置一下我需要的SessionFactory就行了,不过为了每个文件专注一个事情,我又单独配了一个配置文件,而不是 用之前Spring的那一个applicationContext.xml,修改之前的contextConfigLocation,加一个新的文件位 置:
除此之外,hibernate本质上不需要在web.xml里面配置什么,但是有一个属性,我觉得很重要,hibernate对对象的管理是基于 session的,如果开启了延迟加载,对于关联对象的查询可能会在渲染jsp的时候才发生,但是这个时候hibernate的当前session默认已 经关闭了,就会抛异常,所以我们经常需要hibernate在渲染jsp页面的时候还开着session,这就需要在web.xml中配置一个拦截所有请 求的filter:
3. infrastructure.xml
在src/main/resources这个资源包的META-INF目录下创建infrastructure.xml,在这里配置hibernate的SessionFactory:
首先要主意我标称玫红的部分,这是实体类的存放package,hibernate就是用这下面的实体类和数据表对应,需要修改成自己的 package,可以看到这个文件还是比较长,不利于改参数,所以继续抽取一个属性文件出来,property-placeholder就是这个文件的位 置,之后配置一个数据源,用c3p0连接池连接数据库,之后再根据这个数据源配置SessionFactory,进而配置事务,配置 SessionFactory的时候有一个属性hibernate.hbm2dll.auto,是配置根据我们对类的定义自动生成数据表及主外键关系的,
刚创建工程的时候设置成create,以后可以改成update或者删了这个属性(刚建工程的时候就设置成update也可以自己创建数据表,但是不会打 印建表的sql语句),下面来看这个抽取出来的属性文件,在同目录下创建子目录properties,再创建hibernate.properties:
4. applicationContext.xml
还需要改这个文件吗?需要改一点,这个文件之前只有一行:
SSH最基本的代码结构呢,需要有实体类,也就是持久化对象,这是一些和数据表一一对应的类,这些类我们放在domain这个子package下, 然后访问数据库要使用DAO,即数据访问对象,我们为它们创建一个repo包,再加上之前已经有的serivce和controller,基本架子就全 了,所以,不光service要交给spring来管理,repo和domain都要让spring来扫描:
5. domain.User/repo.UserDao/service.UserService
首先在domain包下创建实体类User,我们就用最简单的只有两个字段,id和username:
这里的annotation用的都是JPA的接口,所以都是javax.persistence包下的,annotation加在变量上和 getter方法上都可以,只不过加在public域更好一些,这儿为User对象定义了两个成员,id是主键、自增长,还有一个username,并对 username做了一个限制,比如长度超过6才可以。
之后定义一个dao来访问数据库,创建一个新的package叫做repo(org.zhangfc.demo4ssh.repo),创建UserDao:
创建实现类UserDaoImpl:
首先一个annotation注明这是一个repository,需要被Spring管理,然后自动装载之前在配置文件中配置的 SessionFactory,获取当前session后获取所有的用户,下面修改之前的UserService代码,service封装业务逻辑层代 码,我把每个service方法封装为一个事务,注:上面的SessionFactory获取当前Session是依赖于事务的,如果不在某个事务之内, 会报错:No Session found for current thread。
这个Transactional的annotation就是指明每个方法是一个事务。最后修改HomeController:
<iframe id="cproIframe_u1359759_3" width="728" height="90" src="http://pos.baidu.com/acom?adn=3&at=231&aurl=&cad=1&ccd=24&cec=UTF-8&cfv=18&ch=0&col=zh-CN&conBW=0&conOP=1&cpa=1&dai=3&dis=0<r=https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3D1KlP5qOimLnE1RUHltAaZb2V9SBPLDCDxR16N8nQlznoXdy8VRh7hewGHYIeM3iAyXlMHmrp2v34mE77DuDDKBw2KG5t5vwpRMBjrddpJO7%26wd%3D%26eqid%3D97dd26060000be8d0000000355bb987c<u=http%3A%2F%2Fwww.kwstu.com%2FArticleView%2Fmanong_201411180847365658&lu_161=6&lunum=6&n=13002088_cpr&pcs=1349x622&pis=10000x10000&ps=155x328&psr=1366x768&pss=1349x90&qn=f17e654c8d5c62de&rad=&rsi0=728&rsi1=90&rsi5=4&rss0=%23FFFFFF&rss1=%23FFFFFF&rss2=%230000ff&rss3=%23444444&rss4=%23008000&rss5=&rss6=%23e10900&rss7=&scale=&skin=tabcloud_skin_3&stid=5&td_id=1359759&titFF=%E5%AE%8B%E4%BD%93&titFS=12&titTA=left&tn=text_default_728_90&tpr=1438358165161&ts=1&version=2.0&xuanting=0&dtm=BAIDU_DUP2_SETJSONADSLOT&dc=2&di=u1359759&ti=Springmvc%2BSpring%2BHibernate%E6%90%AD%E5%BB%BA%E6%96%B9%E6%B3%95%E5%8F%8A%E5%AE%9E%E4%BE%8B%20-%20%E7%A8%8B%E5%BA%8F%E5%9B%AD&tt=1438358165110.769.963.963" align="center,center" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" allowtransparency="true" style="list-style: none; margin: 0px; padding: 0px;"></iframe>
<iframe id="cproIframe_u1657523_4" width="160" height="90" src="http://pos.baidu.com/acom?adn=0&at=128&aurl=&cad=1&ccd=24&cec=UTF-8&cfv=18&ch=0&col=zh-CN&conOP=0&cpa=1&dai=4&dis=0<r=https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3D1KlP5qOimLnE1RUHltAaZb2V9SBPLDCDxR16N8nQlznoXdy8VRh7hewGHYIeM3iAyXlMHmrp2v34mE77DuDDKBw2KG5t5vwpRMBjrddpJO7%26wd%3D%26eqid%3D97dd26060000be8d0000000355bb987c<u=http%3A%2F%2Fwww.kwstu.com%2FArticleView%2Fmanong_201411180847365658&lunum=6&n=13002088_cpr&pcs=1349x622&pis=10000x10000&ps=155x1056&psr=1366x768&pss=1349x90&qn=656c46d4c8c9f4df&rad=&rsi0=160&rsi1=90&rsi5=4&rss0=%23FFFFFF&rss1=%23FFFFFF&rss2=%230000ff&rss3=&rss4=&rss5=&rss6=%23e10900&rss7=&scale=&skin=tabcloud_skin_3&stid=5&td_id=1657523&tn=baiduCustSTagLinkUnit&tpr=1438358165161&ts=1&version=2.0&xuanting=0&dtm=BAIDU_DUP2_SETJSONADSLOT&dc=2&di=u1657523&ti=Springmvc%2BSpring%2BHibernate%E6%90%AD%E5%BB%BA%E6%96%B9%E6%B3%95%E5%8F%8A%E5%AE%9E%E4%BE%8B%20-%20%E7%A8%8B%E5%BA%8F%E5%9B%AD&tt=1438358165110.973.1279.1279" align="center,center" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" allowtransparency="true" style="list-style: none; margin: 0px; padding: 0px;"></iframe>
前面两篇文章,分别介绍了Springmvc和Spring的搭建方法,本文再搭建hibernate,并建立SSH最基本的代码结构。
Hibernate和前面两个比就比较复杂了,Hibernate是一个orm的框架,也就是负责面向对象中的对象(Object)和关系型数据库 这个关系(Relation)之间的映射(Mapping)。因为关系型数据库的思维方式,和编程的时候对于对象的理解是有偏差的,所以也有一些面向对象 的数据库,但是随着这些orm框架的完善,面向对象的数据库就销声匿迹了。
当然,我这篇文章也只是搭建环境,并不多讲annotation,这个会专门写一篇来讲。
闲话少说,第一步是安装好数据库,我用的是mysql,安装在本地,本开启了mysql服务。之后看程序怎么改进。
1. pom.xml
第一步加入hibernate的相关jar包,首先在properties标签下面定义一个版本:
然后加入hibernate的核心包,因为要让Spring管理一些对象,还要引入spring-orm的包:
除此之外,因为我们要用mysql数据库,并使用c3p0连接池,因此需要引入这两个对应的包:
2. web.xml
hibernate有两种使用方法,一种是通过一个SessionFactory来获取Session,还有一种是通过 EntityManagerFactory来获取entityManager,我忘了什么原因了,刚开始用的EntityManager后来换回了 SessionFactory(hibernate3以前用的是SessionFactory),我后面的描述也都是基于sessionFactory 了。而不管是Session还是EntityManager,我们都要去创建和管理这个对象,当然,有了Spring,这个事情就不用我们来操心了,只需
要在Spring的配置文件里面配置一下我需要的SessionFactory就行了,不过为了每个文件专注一个事情,我又单独配了一个配置文件,而不是 用之前Spring的那一个applicationContext.xml,修改之前的contextConfigLocation,加一个新的文件位 置:
除此之外,hibernate本质上不需要在web.xml里面配置什么,但是有一个属性,我觉得很重要,hibernate对对象的管理是基于 session的,如果开启了延迟加载,对于关联对象的查询可能会在渲染jsp的时候才发生,但是这个时候hibernate的当前session默认已 经关闭了,就会抛异常,所以我们经常需要hibernate在渲染jsp页面的时候还开着session,这就需要在web.xml中配置一个拦截所有请 求的filter:
3. infrastructure.xml
在src/main/resources这个资源包的META-INF目录下创建infrastructure.xml,在这里配置hibernate的SessionFactory:
首先要主意我标称玫红的部分,这是实体类的存放package,hibernate就是用这下面的实体类和数据表对应,需要修改成自己的 package,可以看到这个文件还是比较长,不利于改参数,所以继续抽取一个属性文件出来,property-placeholder就是这个文件的位 置,之后配置一个数据源,用c3p0连接池连接数据库,之后再根据这个数据源配置SessionFactory,进而配置事务,配置 SessionFactory的时候有一个属性hibernate.hbm2dll.auto,是配置根据我们对类的定义自动生成数据表及主外键关系的,
刚创建工程的时候设置成create,以后可以改成update或者删了这个属性(刚建工程的时候就设置成update也可以自己创建数据表,但是不会打 印建表的sql语句),下面来看这个抽取出来的属性文件,在同目录下创建子目录properties,再创建hibernate.properties:
4. applicationContext.xml
还需要改这个文件吗?需要改一点,这个文件之前只有一行:
SSH最基本的代码结构呢,需要有实体类,也就是持久化对象,这是一些和数据表一一对应的类,这些类我们放在domain这个子package下, 然后访问数据库要使用DAO,即数据访问对象,我们为它们创建一个repo包,再加上之前已经有的serivce和controller,基本架子就全 了,所以,不光service要交给spring来管理,repo和domain都要让spring来扫描:
5. domain.User/repo.UserDao/service.UserService
首先在domain包下创建实体类User,我们就用最简单的只有两个字段,id和username:
这里的annotation用的都是JPA的接口,所以都是javax.persistence包下的,annotation加在变量上和 getter方法上都可以,只不过加在public域更好一些,这儿为User对象定义了两个成员,id是主键、自增长,还有一个username,并对 username做了一个限制,比如长度超过6才可以。
之后定义一个dao来访问数据库,创建一个新的package叫做repo(org.zhangfc.demo4ssh.repo),创建UserDao:
创建实现类UserDaoImpl:
首先一个annotation注明这是一个repository,需要被Spring管理,然后自动装载之前在配置文件中配置的 SessionFactory,获取当前session后获取所有的用户,下面修改之前的UserService代码,service封装业务逻辑层代 码,我把每个service方法封装为一个事务,注:上面的SessionFactory获取当前Session是依赖于事务的,如果不在某个事务之内, 会报错:No Session found for current thread。
这个Transactional的annotation就是指明每个方法是一个事务。最后修改HomeController:
Hibernate和前面两个比就比较复杂了,Hibernate是一个orm的框架,也就是负责面向对象中的对象(Object)和关系型数据库 这个关系(Relation)之间的映射(Mapping)。因为关系型数据库的思维方式,和编程的时候对于对象的理解是有偏差的,所以也有一些面向对象 的数据库,但是随着这些orm框架的完善,面向对象的数据库就销声匿迹了。
当然,我这篇文章也只是搭建环境,并不多讲annotation,这个会专门写一篇来讲。
闲话少说,第一步是安装好数据库,我用的是mysql,安装在本地,本开启了mysql服务。之后看程序怎么改进。
1. pom.xml
第一步加入hibernate的相关jar包,首先在properties标签下面定义一个版本:
<properties> <spring.version>4.0.4.RELEASE</spring.version> <hibernate.version>4.3.5.Final</hibernate.version> </properties>
然后加入hibernate的核心包,因为要让Spring管理一些对象,还要引入spring-orm的包:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency>
除此之外,因为我们要用mysql数据库,并使用c3p0连接池,因此需要引入这两个对应的包:
<dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.31</version> </dependency>
2. web.xml
hibernate有两种使用方法,一种是通过一个SessionFactory来获取Session,还有一种是通过 EntityManagerFactory来获取entityManager,我忘了什么原因了,刚开始用的EntityManager后来换回了 SessionFactory(hibernate3以前用的是SessionFactory),我后面的描述也都是基于sessionFactory 了。而不管是Session还是EntityManager,我们都要去创建和管理这个对象,当然,有了Spring,这个事情就不用我们来操心了,只需
要在Spring的配置文件里面配置一下我需要的SessionFactory就行了,不过为了每个文件专注一个事情,我又单独配了一个配置文件,而不是 用之前Spring的那一个applicationContext.xml,修改之前的contextConfigLocation,加一个新的文件位 置:
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/META-INF/applicationContext.xml, classpath:/META-INF/infrastructure.xml</param-value> </context-param>
除此之外,hibernate本质上不需要在web.xml里面配置什么,但是有一个属性,我觉得很重要,hibernate对对象的管理是基于 session的,如果开启了延迟加载,对于关联对象的查询可能会在渲染jsp的时候才发生,但是这个时候hibernate的当前session默认已 经关闭了,就会抛异常,所以我们经常需要hibernate在渲染jsp页面的时候还开着session,这就需要在web.xml中配置一个拦截所有请 求的filter:
<filter> <filter-name>hibernateFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>hibernateFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
3. infrastructure.xml
在src/main/resources这个资源包的META-INF目录下创建infrastructure.xml,在这里配置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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <context:property-placeholder location="classpath:/META-INF/properties/hibernate.properties" /> <!-- 使用C3P0数据源,MySQL数据库 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <!-- MySQL5 --> <property n 4000 ame="driverClass" value="${driverClassName}"></property> <property name="jdbcUrl" value="${url}"></property> <property name="user" value="${username}"></property> <property name="password" value="${password}"></property> <property name="maxPoolSize" value="40"></property> <property name="minPoolSize" value="1"></property> <property name="initialPoolSize" value="1"></property> <property name="maxIdleTime" value="20"></property> </bean> <!-- session工厂 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan" value="org.zhangfc.demo4ssh.domain" /> <property name="hibernateProperties"> <props> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
首先要主意我标称玫红的部分,这是实体类的存放package,hibernate就是用这下面的实体类和数据表对应,需要修改成自己的 package,可以看到这个文件还是比较长,不利于改参数,所以继续抽取一个属性文件出来,property-placeholder就是这个文件的位 置,之后配置一个数据源,用c3p0连接池连接数据库,之后再根据这个数据源配置SessionFactory,进而配置事务,配置 SessionFactory的时候有一个属性hibernate.hbm2dll.auto,是配置根据我们对类的定义自动生成数据表及主外键关系的,
刚创建工程的时候设置成create,以后可以改成update或者删了这个属性(刚建工程的时候就设置成update也可以自己创建数据表,但是不会打 印建表的sql语句),下面来看这个抽取出来的属性文件,在同目录下创建子目录properties,再创建hibernate.properties:
hibernate.dialect=org.hibernate.dialect.MySQLDialect driverClassName=com.mysql.jdbc.Driver validationQuery=SELECT 1 url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8 username=root password= hibernate.hbm2ddl.auto=create hibernate.show_sql=true hibernate.format_sql=true
4. applicationContext.xml
还需要改这个文件吗?需要改一点,这个文件之前只有一行:
<context:component-scan base-package="org.zhangfc.demo4ssh.service"/>
SSH最基本的代码结构呢,需要有实体类,也就是持久化对象,这是一些和数据表一一对应的类,这些类我们放在domain这个子package下, 然后访问数据库要使用DAO,即数据访问对象,我们为它们创建一个repo包,再加上之前已经有的serivce和controller,基本架子就全 了,所以,不光service要交给spring来管理,repo和domain都要让spring来扫描:
<context:component-scan base-package="org.zhangfc.demo4ssh.service"/> <context:component-scan base-package="org.zhangfc.demo4ssh.domain"/> <context:component-scan base-package="org.zhangfc.demo4ssh.repo"/>
5. domain.User/repo.UserDao/service.UserService
首先在domain包下创建实体类User,我们就用最简单的只有两个字段,id和username:
@Entity @Table public class User implements Serializable { private static final long serialVersionUID = 172643386440351811L; private int id; private String username; @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } @Size(min=6) public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
这里的annotation用的都是JPA的接口,所以都是javax.persistence包下的,annotation加在变量上和 getter方法上都可以,只不过加在public域更好一些,这儿为User对象定义了两个成员,id是主键、自增长,还有一个username,并对 username做了一个限制,比如长度超过6才可以。
之后定义一个dao来访问数据库,创建一个新的package叫做repo(org.zhangfc.demo4ssh.repo),创建UserDao:
public interface UserDao { public int save(User u); public List<User> findAll(); }
创建实现类UserDaoImpl:
@Repository public class UserDaoImpl implements UserDao { @Autowired private SessionFactory sessionFactory; public List<User> findAll() { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(User.class); return criteria.list(); } }
首先一个annotation注明这是一个repository,需要被Spring管理,然后自动装载之前在配置文件中配置的 SessionFactory,获取当前session后获取所有的用户,下面修改之前的UserService代码,service封装业务逻辑层代 码,我把每个service方法封装为一个事务,注:上面的SessionFactory获取当前Session是依赖于事务的,如果不在某个事务之内, 会报错:No Session found for current thread。
UserService: public interface UserService { public void saveUsers(List<User> us); public List<User> getAllUsers(); } UserServiceImpl:
@Service @Transactional public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; public void saveUsers(List<User> us) { for (User u : us) { userDao.save(u); } } public List<User> getAllUsers() { return userDao.findAll(); } }
这个Transactional的annotation就是指明每个方法是一个事务。最后修改HomeController:
@RequestMapping("") public String home(){ List<User> us = new ArrayList<User>(); User u = new User(); u.setUsername("zhangsan"); us.add(u); u = new User(); u.setUsername("wangwu"); us.add(u); userService.saveUsers(us); return "index"; } @RequestMapping("/json") @ResponseBody public List<User> json(){ return userService.getAllUsers(); }
<iframe id="cproIframe_u1359759_3" width="728" height="90" src="http://pos.baidu.com/acom?adn=3&at=231&aurl=&cad=1&ccd=24&cec=UTF-8&cfv=18&ch=0&col=zh-CN&conBW=0&conOP=1&cpa=1&dai=3&dis=0<r=https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3D1KlP5qOimLnE1RUHltAaZb2V9SBPLDCDxR16N8nQlznoXdy8VRh7hewGHYIeM3iAyXlMHmrp2v34mE77DuDDKBw2KG5t5vwpRMBjrddpJO7%26wd%3D%26eqid%3D97dd26060000be8d0000000355bb987c<u=http%3A%2F%2Fwww.kwstu.com%2FArticleView%2Fmanong_201411180847365658&lu_161=6&lunum=6&n=13002088_cpr&pcs=1349x622&pis=10000x10000&ps=155x328&psr=1366x768&pss=1349x90&qn=f17e654c8d5c62de&rad=&rsi0=728&rsi1=90&rsi5=4&rss0=%23FFFFFF&rss1=%23FFFFFF&rss2=%230000ff&rss3=%23444444&rss4=%23008000&rss5=&rss6=%23e10900&rss7=&scale=&skin=tabcloud_skin_3&stid=5&td_id=1359759&titFF=%E5%AE%8B%E4%BD%93&titFS=12&titTA=left&tn=text_default_728_90&tpr=1438358165161&ts=1&version=2.0&xuanting=0&dtm=BAIDU_DUP2_SETJSONADSLOT&dc=2&di=u1359759&ti=Springmvc%2BSpring%2BHibernate%E6%90%AD%E5%BB%BA%E6%96%B9%E6%B3%95%E5%8F%8A%E5%AE%9E%E4%BE%8B%20-%20%E7%A8%8B%E5%BA%8F%E5%9B%AD&tt=1438358165110.769.963.963" align="center,center" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" allowtransparency="true" style="list-style: none; margin: 0px; padding: 0px;"></iframe>
<iframe id="cproIframe_u1657523_4" width="160" height="90" src="http://pos.baidu.com/acom?adn=0&at=128&aurl=&cad=1&ccd=24&cec=UTF-8&cfv=18&ch=0&col=zh-CN&conOP=0&cpa=1&dai=4&dis=0<r=https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3D1KlP5qOimLnE1RUHltAaZb2V9SBPLDCDxR16N8nQlznoXdy8VRh7hewGHYIeM3iAyXlMHmrp2v34mE77DuDDKBw2KG5t5vwpRMBjrddpJO7%26wd%3D%26eqid%3D97dd26060000be8d0000000355bb987c<u=http%3A%2F%2Fwww.kwstu.com%2FArticleView%2Fmanong_201411180847365658&lunum=6&n=13002088_cpr&pcs=1349x622&pis=10000x10000&ps=155x1056&psr=1366x768&pss=1349x90&qn=656c46d4c8c9f4df&rad=&rsi0=160&rsi1=90&rsi5=4&rss0=%23FFFFFF&rss1=%23FFFFFF&rss2=%230000ff&rss3=&rss4=&rss5=&rss6=%23e10900&rss7=&scale=&skin=tabcloud_skin_3&stid=5&td_id=1657523&tn=baiduCustSTagLinkUnit&tpr=1438358165161&ts=1&version=2.0&xuanting=0&dtm=BAIDU_DUP2_SETJSONADSLOT&dc=2&di=u1657523&ti=Springmvc%2BSpring%2BHibernate%E6%90%AD%E5%BB%BA%E6%96%B9%E6%B3%95%E5%8F%8A%E5%AE%9E%E4%BE%8B%20-%20%E7%A8%8B%E5%BA%8F%E5%9B%AD&tt=1438358165110.973.1279.1279" align="center,center" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" allowtransparency="true" style="list-style: none; margin: 0px; padding: 0px;"></iframe>
前面两篇文章,分别介绍了Springmvc和Spring的搭建方法,本文再搭建hibernate,并建立SSH最基本的代码结构。
Hibernate和前面两个比就比较复杂了,Hibernate是一个orm的框架,也就是负责面向对象中的对象(Object)和关系型数据库 这个关系(Relation)之间的映射(Mapping)。因为关系型数据库的思维方式,和编程的时候对于对象的理解是有偏差的,所以也有一些面向对象 的数据库,但是随着这些orm框架的完善,面向对象的数据库就销声匿迹了。
当然,我这篇文章也只是搭建环境,并不多讲annotation,这个会专门写一篇来讲。
闲话少说,第一步是安装好数据库,我用的是mysql,安装在本地,本开启了mysql服务。之后看程序怎么改进。
1. pom.xml
第一步加入hibernate的相关jar包,首先在properties标签下面定义一个版本:
<properties> <spring.version>4.0.4.RELEASE</spring.version> <hibernate.version>4.3.5.Final</hibernate.version> </properties>
然后加入hibernate的核心包,因为要让Spring管理一些对象,还要引入spring-orm的包:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency>
除此之外,因为我们要用mysql数据库,并使用c3p0连接池,因此需要引入这两个对应的包:
<dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.31</version> </dependency>
2. web.xml
hibernate有两种使用方法,一种是通过一个SessionFactory来获取Session,还有一种是通过 EntityManagerFactory来获取entityManager,我忘了什么原因了,刚开始用的EntityManager后来换回了 SessionFactory(hibernate3以前用的是SessionFactory),我后面的描述也都是基于sessionFactory 了。而不管是Session还是EntityManager,我们都要去创建和管理这个对象,当然,有了Spring,这个事情就不用我们来操心了,只需
要在Spring的配置文件里面配置一下我需要的SessionFactory就行了,不过为了每个文件专注一个事情,我又单独配了一个配置文件,而不是 用之前Spring的那一个applicationContext.xml,修改之前的contextConfigLocation,加一个新的文件位 置:
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/META-INF/applicationContext.xml, classpath:/META-INF/infrastructure.xml</param-value> </context-param>
除此之外,hibernate本质上不需要在web.xml里面配置什么,但是有一个属性,我觉得很重要,hibernate对对象的管理是基于 session的,如果开启了延迟加载,对于关联对象的查询可能会在渲染jsp的时候才发生,但是这个时候hibernate的当前session默认已 经关闭了,就会抛异常,所以我们经常需要hibernate在渲染jsp页面的时候还开着session,这就需要在web.xml中配置一个拦截所有请 求的filter:
<filter> <filter-name>hibernateFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>hibernateFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
3. infrastructure.xml
在src/main/resources这个资源包的META-INF目录下创建infrastructure.xml,在这里配置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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <context:property-placeholder location="classpath:/META-INF/properties/hibernate.properties" /> <!-- 使用C3P0数据源,MySQL数据库 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <!-- MySQL5 --> <property name="driverClass" value="${driverClassName}"></property> <property name="jdbcUrl" value="${url}"></property> <property name="user" value="${username}"></property> <property name="password" value="${password}"></property> <property name="maxPoolSize" value="40"></property> <property name="minPoolSize" value="1"></property> <property name="initialPoolSize" value="1"></property> <property name="maxIdleTime" value="20"></property> </bean> <!-- session工厂 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan" value="org.zhangfc.demo4ssh.domain" /> <property name="hibernateProperties"> <props> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
首先要主意我标称玫红的部分,这是实体类的存放package,hibernate就是用这下面的实体类和数据表对应,需要修改成自己的 package,可以看到这个文件还是比较长,不利于改参数,所以继续抽取一个属性文件出来,property-placeholder就是这个文件的位 置,之后配置一个数据源,用c3p0连接池连接数据库,之后再根据这个数据源配置SessionFactory,进而配置事务,配置 SessionFactory的时候有一个属性hibernate.hbm2dll.auto,是配置根据我们对类的定义自动生成数据表及主外键关系的,
刚创建工程的时候设置成create,以后可以改成update或者删了这个属性(刚建工程的时候就设置成update也可以自己创建数据表,但是不会打 印建表的sql语句),下面来看这个抽取出来的属性文件,在同目录下创建子目录properties,再创建hibernate.properties:
hibernate.dialect=org.hibernate.dialect.MySQLDialect driverClassName=com.mysql.jdbc.Driver validationQuery=SELECT 1 url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8 username=root password= hibernate.hbm2ddl.auto=create hibernate.show_sql=true hibernate.format_sql=true
4. applicationContext.xml
还需要改这个文件吗?需要改一点,这个文件之前只有一行:
<context:component-scan base-package="org.zhangfc.demo4ssh.service"/>
SSH最基本的代码结构呢,需要有实体类,也就是持久化对象,这是一些和数据表一一对应的类,这些类我们放在domain这个子package下, 然后访问数据库要使用DAO,即数据访问对象,我们为它们创建一个repo包,再加上之前已经有的serivce和controller,基本架子就全 了,所以,不光service要交给spring来管理,repo和domain都要让spring来扫描:
<context:component-scan base-package="org.zhangfc.demo4ssh.service"/> <context:component-scan base-package="org.zhangfc.demo4ssh.domain"/> <context:component-scan base-package="org.zhangfc.demo4ssh.repo"/>
5. domain.User/repo.UserDao/service.UserService
首先在domain包下创建实体类User,我们就用最简单的只有两个字段,id和username:
@Entity @Table public class User implements Serializable { private static final long serialVersionUID = 172643386440351811L; private int id; private String username; @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } @Size(min=6) public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
这里的annotation用的都是JPA的接口,所以都是javax.persistence包下的,annotation加在变量上和 getter方法上都可以,只不过加在public域更好一些,这儿为User对象定义了两个成员,id是主键、自增长,还有一个username,并对 username做了一个限制,比如长度超过6才可以。
之后定义一个dao来访问数据库,创建一个新的package叫做repo(org.zhangfc.demo4ssh.repo),创建UserDao:
public interface UserDao { public int save(User u); public List<User> findAll(); }
创建实现类UserDaoImpl:
@Repository public class UserDaoImpl implements UserDao { @Autowired private SessionFactory sessionFactory; public List<User> findAll() { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(User.class); return criteria.list(); } }
首先一个annotation注明这是一个repository,需要被Spring管理,然后自动装载之前在配置文件中配置的 SessionFactory,获取当前session后获取所有的用户,下面修改之前的UserService代码,service封装业务逻辑层代 码,我把每个service方法封装为一个事务,注:上面的SessionFactory获取当前Session是依赖于事务的,如果不在某个事务之内, 会报错:No Session found for current thread。
UserService: public interface UserService { public void saveUsers(List<User> us); public List<User> getAllUsers(); } UserServiceImpl:
@Service @Transactional public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; public void saveUsers(List<User> us) { for (User u : us) { userDao.save(u); } } public List<User> getAllUsers() { return userDao.findAll(); } }
这个Transactional的annotation就是指明每个方法是一个事务。最后修改HomeController:
@RequestMapping("") public String home(){ List<User> us = new ArrayList<User>(); User u = new User(); u.setUsername("zhangsan"); us.add(u); u = new User(); u.setUsername("wangwu"); us.add(u); userService.saveUsers(us); return "index"; } @RequestMapping("/json") @ResponseBody public List<User> json(){ return userService.getAllUsers(); }
相关文章推荐
- struts2的default.properties详解
- 定制Eclipse IDE之界面篇
- 5 class design principles [S.O.L.I.D.] in java
- SpringMVC+Spring+Hibernate配置
- 多租户--EclipseLink实现
- 转:OpenJDK和SunJDK的区别和联系
- EasyUI+SpringMVC配置session过期跳转页面
- 菜鸟好文推荐(十二)——Java集合的小抄 Java初学者必备
- java常用容器(集合)的总结
- 关于java日期类Date,DateFormat,SimpleDateFormat,Calendar总结
- Java--接口
- Eclipse OSGi调试过程
- java中UDP传输协议
- 转:JRE与JDK的区别详解
- Java--类
- SpringMVC:Name for argument type ERROR
- Eclipse Mark Occurrences
- Eclipse spket插件 内置js文件
- Struts2 零配置(二)—约定大于配置
- 【JAVA】浅谈java内部类