前言
今天复习一下SpringMVC+Hibernate的搭建,本来想着将Spring-Security权限控制框架也映入其中的,但是发现内容太多了,Spring-Security的就留在下一篇吧,这篇主要搭建SpringMVC4.1.4和Hibernate4.3.8,之前也打了好多SpringMVC的,这部分已经非常的熟悉了,毕竟业开发过一年多SpringMVC的,这次持久层采用Hibernate,数据源采用c3p0,数据库暂采用MySQL,主要是想复习一下Hibernate。搭建SpringMVC+Hibernate的框架的思路如下:
1、设计数据库:设计好表结构,最好符合3NF,采用Hibernate tools将设计好的表自动生成对应的实体entity。
1、创建Maven项目,按需映入Maven包依赖。
2、搭建Spring:配置Spring对控件层Bean的注入。
3、搭建Hibernate:配置数据源,配置SessionFactory,配置事务,以及二级缓存ehcache的配置。
4、测试Spring+Hibernate的框架搭建,写单元测试JUnit,测试事务配置等。
5、映入SpringMVC:配置SpringMVC配置信息。
6、配置web.xml容器
7、测试三个框架的整合:Maven编译打包部署服务器,测试。
1、数据库设计
设计一个权限、角色、用户的表。自然如果一个用户可以有多个角色,一个角色多个用户所拥有;一个角色拥有多个权限,一个权限对应多个角色。所以按照数据库表结构设计,符合3NF的话我们需要5张表进行存在。表的具体信息就不列出了(可以下在源码,里面还有数据库),表关系如下:
这里面ID才用到是java的UUID(36位)
2、创建Maven项目,编写pom.xml文件
创建一个Maven的webapp项目,编写pom.xml文件,引入所需的包依赖,我这里就将所需的全部的映入了。
pom.xml文件内容如下:
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.andy.sh</groupId>
- <artifactId>springmvc_hibernate_demo</artifactId>
- <packaging>war</packaging>
- <version>0.0.1-SNAPSHOT</version>
- <name>springmvc_hibernate_demo Maven Webapp</name>
- <url>http://maven.apache.org</url>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <spring.version>4.1.4.RELEASE</spring.version>
- <hibernate.version>4.3.8.Final</hibernate.version>
- <jackson.version>2.5.0</jackson.version>
- </properties>
- <dependencies>
- <!-- junit -->
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.12</version>
- <scope>test</scope>
- </dependency>
- <!-- spring -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-core</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-beans</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-tx</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
- <version>${spring.version}</version>
- <scope>test</scope>
- </dependency>
- <!-- 使用SpringMVC需配置 -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <!-- 关系型数据库整合时需配置 如hibernate jpa等 -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-orm</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <!-- hibernate -->
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-core</artifactId>
- <version>${hibernate.version}</version>
- </dependency>
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-ehcache</artifactId>
- <version>${hibernate.version}</version>
- </dependency>
- <!-- 二级缓存ehcache -->
- <dependency>
- <groupId>net.sf.ehcache</groupId>
- <artifactId>ehcache</artifactId>
- <version>2.9.0</version>
- </dependency>
- <!-- log4j -->
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>1.2.17</version>
- </dependency>
- <!-- mysql连接 -->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.34</version>
- </dependency>
- <!-- c3p0数据源 -->
- <dependency>
- <groupId>com.mchange</groupId>
- <artifactId>c3p0</artifactId>
- <version>0.9.5-pre10</version>
- </dependency>
- <!-- json -->
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>fastjson</artifactId>
- <version>1.2.3</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-annotations</artifactId>
- <version>${jackson.version}</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-core</artifactId>
- <version>${jackson.version}</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>${jackson.version}</version>
- </dependency>
- <!-- aop -->
- <dependency>
- <groupId>org.aspectj</groupId>
- <artifactId>aspectjweaver</artifactId>
- <version>1.8.4</version>
- </dependency>
- <!-- servlet -->
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <version>3.0-alpha-1</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>jstl</artifactId>
- <version>1.2</version>
- </dependency>
- </dependencies>
- <build>
- <finalName>springmvc_hibernate_demo</finalName>
- <plugins>
- <!-- Run the JUnit unit tests in an isolated classloader -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <version>2.4.2</version>
- <configuration>
- <skipTests>true</skipTests>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-war-plugin</artifactId>
- <version>2.3</version>
- <configuration>
- <webXml>src/main/webapp/WEB-INF/web.xml</webXml>
- </configuration>
- </plugin>
- <!-- generate java doc -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-javadoc-plugin</artifactId>
- <version>2.9.1</version>
- <configuration>
- <javadocDirectory>target/javadoc</javadocDirectory>
- <reportOutputDirectory>target/javadoc</reportOutputDirectory>
- <charset>UTF-8</charset>
- <encoding>UTF-8</encoding>
- <docencoding>UTF-8</docencoding>
- <show>private</show>
- </configuration>
- </plugin>
- <!-- 部署至本机 -->
- <plugin>
- <groupId>org.codehaus.cargo</groupId>
- <artifactId>cargo-maven2-plugin</artifactId>
- <version>1.0</version>
- <configuration>
- <container>
- <containerId>tomcat6x</containerId>
- <home>D:\WebServer\apache-tomcat-6.0.39</home>
- </container>
- <configuration>
- <type>existing</type>
- <home>D:\WebServer\apache-tomcat-6.0.39</home>
- </configuration>
- </configuration>
- </plugin>
- </plugins>
- </build>
- </project>
3、引入Spring配置
编写配置文件,配置文件放在src/main/resources资源目录下(下同)。
项目所需的配置信息config.properties
- #application configs
- #jdbc c3p0 config
- jdbc.driver = com.mysql.jdbc.Driver
- jdbc.url = jdbc:mysql://localhost:3306/work?useUnicode=true&characterEncoding=utf-8
- jdbc.username = root
- jdbc.password = 12345
- #hibernate config
- hibernate.dialect = org.hibernate.dialect.MySQLDialect
- hibernate.show_sql = true
- hibernate.format_sql = false
- hibernate.hbm2ddl.auto = update
- hibernate.cache.use_second_level_cache = true
- hibernate.cache.use_query_cache = true
- hibernate.cache.region.factory_class = org.hibernate.cache.ehcache.EhCacheRegionFactory
- hibernate.cache.provider_configuration_file_resource_path = ehcache.xml
3.1、spring配置
spring.xml的配置文件如下:
- <?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:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-4.1.xsd">
- <!-- 加载配置文件 -->
- <context:property-placeholder location="classpath:config.properties"/>
- <!-- 扫描service自动注入为bean -->
- <context:component-scan base-package="org.andy.work.service.impl,org.andy.work.dao.impl" />
- </beans>
上面spring配置了对应包下组件bean自动注入管理,我们需要将dao,service的实现类交由spring管理,如(@Repository,@Service)。
3.2、引入日志文件配置Log4j
log4j.properties的配置文件如下:
- ### set log levels ###
- log4j.rootLogger = INFO , C , D , E
- ### console ###
- log4j.appender.C = org.apache.log4j.ConsoleAppender
- log4j.appender.C.Target = System.out
- log4j.appender.C.layout = org.apache.log4j.PatternLayout
- log4j.appender.C.layout.ConversionPattern = [springmvc_hibernate_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
- ### log file ###
- log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
- log4j.appender.D.File = ../logs/springmvc_hibernate_demo.log
- log4j.appender.D.Append = true
- log4j.appender.D.Threshold = INFO
- log4j.appender.D.layout = org.apache.log4j.PatternLayout
- log4j.appender.D.layout.ConversionPattern = [springmvc_hibernate_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
- ### exception ###
- log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
- log4j.appender.E.File = ../logs/springmvc_hibernate_demo_error.log
- log4j.appender.E.Append = true
- log4j.appender.E.Threshold = ERROR
- log4j.appender.E.layout = org.apache.log4j.PatternLayout
- log4j.appender.E.layout.ConversionPattern = [sspringmvc_hibernate_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
4、Hibernate配置
Hibernate的配置主要包括:配置数据源c3p0,配置SessionFactory,配置事务管理器,配置事务管理,其spring-hibernate.xml文件如下:
- <?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"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
- <!-- 配置数据源 c3p0 -->
- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
- destroy-method="close">
- <property name="driverClass" value="${jdbc.driver}" />
- <property name="jdbcUrl" value="${jdbc.url}" />
- <property name="user" value="${jdbc.username}" />
- <property name="password" value="${jdbc.password}" />
- <!-- 请求超时时间 -->
- <property name="checkoutTimeout" value="30000" />
- <!-- 每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 -->
- <property name="idleConnectionTestPeriod" value="30" />
- <!-- 连接数据库连接池最大空闲时间 -->
- <property name="maxIdleTime" value="30" />
- <!-- 连接池初始化连接数 -->
- <property name="initialPoolSize" value="5" />
- <property name="minPoolSize" value="5" />
- <property name="maxPoolSize" value="20" />
- <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 -->
- <property name="acquireIncrement" value="5" />
- </bean>
- <!-- 配置hibernate的SessionFactory -->
- <bean id="sessionFactory"
- class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
- <!-- 注入数据源 相关信息看源码 -->
- <property name="dataSource" ref="dataSource" />
- <!-- hibernate配置信息 -->
- <property name="hibernateProperties">
- <props>
- <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>
- <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
- <!-- 开启二级缓存 ehcache -->
- <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
- <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
- <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>
- <prop key="hibernate.cache.provider_configuration_file_resource_path">${hibernate.cache.provider_configuration_file_resource_path}
- </prop>
- </props>
- </property>
- <!-- 扫描hibernate注解配置的entity -->
- <property name="packagesToScan" value="org.andy.work.entity" />
- </bean>
- <!-- 配置事务管理器 -->
- <bean id="transactionManager"
- class="org.springframework.orm.hibernate4.HibernateTransactionManager">
- <property name="sessionFactory" ref="sessionFactory" />
- </bean>
- <!-- 配置事务增强处理Bean,指定事务管理器 -->
- <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
- <!-- 配置详细事务处理语义 -->
- <tx:attributes>
- <tx:method name="insert*" propagation="REQUIRED" />
- <tx:method name="update*" propagation="REQUIRED" />
- <tx:method name="delete*" propagation="REQUIRED" />
- <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
- <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
- <tx:method name="select*" propagation="SUPPORTS" read-only="true" />
- <tx:method name="load*" propagation="SUPPORTS" read-only="true" />
- <!-- 其他采用默认事务方式 -->
- <tx:method name="*" />
- </tx:attributes>
- </tx:advice>
- <!-- Spring aop事务管理 -->
- <aop:config>
- <!-- 配置切入点 -->
- <aop:pointcut id="transactionPointcut"
- expression="execution(* org.andy.work.service..*Impl.*(..))" />
- <!-- 指定在txAdvice切入点应用txAdvice事务增强处理 -->
- <aop:advisor pointcut-ref="transactionPointcut"
- advice-ref="transactionAdvice" />
- </aop:config>
- </beans>
上面配置了二级缓存,ehcache,相关的具体信息查看上一篇Hibernate二级缓存以及ehcache的搭建配置,下面是二级缓存的配置。
4.1、ehcache.xml的配置
- <?xml version="1.0" encoding="UTF-8"?>
- <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
- <diskStore path="D:/ehcache" />
- <!-- DefaultCache setting. -->
- <defaultCache
- maxElementsInMemory="1000"
- eternal="false"
- timeToIdleSeconds="120"
- timeToLiveSeconds="120"
- maxElementsOnDisk="1000000"
- overflowToDisk="true"
- memoryStoreEvictionPolicy="LRU">
- </defaultCache>
- <!-- Special objects setting. -->
- <cache
- name="org.andy.work.entity.AcctUser"
- maxElementsInMemory="2"
- memoryStoreEvictionPolicy="LRU"
- eternal="true"
- diskPersistent="false"
- overflowToDisk="false"
- maxElementsOnDisk="1000000" />
- </ehcache>
上面Hibernate二级缓存ehcache存放磁盘是D:/ehcache
5、生成业务entity实体
设计好数据表后,Hibernate的实体有工具Hibernate tools自动生成,Eclipse需要安装Hibernate tools插件(我在线安装过几次都不成功,推荐使用links离线安装,附录将介绍),所以不需要手工的书写,下面就贴一个用户信息的实体,AcctUser.java
- package org.andy.work.entity;
- // Generated 2015-2-3 10:43:00 by Hibernate Tools 4.0.0
- import java.util.Date;
- import java.util.HashSet;
- import java.util.Set;
- import javax.persistence.Column;
- import javax.persistence.Entity;
- import javax.persistence.FetchType;
- import javax.persistence.Id;
- import javax.persistence.JoinColumn;
- import javax.persistence.JoinTable;
- import javax.persistence.ManyToMany;
- import javax.persistence.Table;
- import javax.persistence.Temporal;
- import javax.persistence.TemporalType;
- import org.hibernate.annotations.Cache;
- import org.hibernate.annotations.CacheConcurrencyStrategy;
- import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
- /**
- * AcctUser generated by hbm2java
- */
- @Entity
- @Table(name = "acct_user", catalog = "work")
- @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- public class AcctUser implements java.io.Serializable {
- /**
- *
- */
- private static final long serialVersionUID = 6980093847795726310L;
- private String id;
- private String nickName;
- private String telephone;
- private Date registerTime;
- private Set<AcctRole> acctRoles = new HashSet<AcctRole>(0);
- public AcctUser() {
- }
- public AcctUser(String id, String nickName) {
- this.id = id;
- this.nickName = nickName;
- }
- public AcctUser(String id, String nickName, String telephone,
- Date registerTime, Set<AcctRole> acctRoles) {
- this.id = id;
- this.nickName = nickName;
- this.telephone = telephone;
- this.registerTime = registerTime;
- this.acctRoles = acctRoles;
- }
- @Id
- @Column(name = "id", unique = true, nullable = false, length = 36)
- public String getId() {
- return this.id;
- }
- public void setId(String id) {
- this.id = id;
- }
- @Column(name = "nick_name", nullable = false)
- public String getNickName() {
- return this.nickName;
- }
- public void setNickName(String nickName) {
- this.nickName = nickName;
- }
- @Column(name = "telephone")
- public String getTelephone() {
- return this.telephone;
- }
- public void setTelephone(String telephone) {
- this.telephone = telephone;
- }
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "register_time", length = 19)
- public Date getRegisterTime() {
- return this.registerTime;
- }
- public void setRegisterTime(Date registerTime) {
- this.registerTime = registerTime;
- }
- @JsonIgnoreProperties(value={"acctUsers", "acctAuthorities"})
- @ManyToMany(fetch = FetchType.LAZY)
- @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- @JoinTable(name = "acct_user_role", catalog = "work", joinColumns = { @JoinColumn(name = "user_id", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "role_id", nullable = false, updatable = false) })
- public Set<AcctRole> getAcctRoles() {
- return this.acctRoles;
- }
- public void setAcctRoles(Set<AcctRole> acctRoles) {
- this.acctRoles = acctRoles;
- }
- }
上面有几个需要注意的:
上面大多数都是Hibernate tools自动生成的,但是有几个需要手动添加:
1、如果这个实体使用二级缓存的话,需要添加@cache注解;
2、如果该实体里面还有集合元素(set, map,list),如果实体要采用二级缓存,那么这些集合元素必须也添加@cache注解。
3、@JsonIgnoreProperties注解是为了防止SpringMVC在json返回时产生循环输出使用,如果不配置的话就会出现json死循环(还有多对多,一对多的属性时)。
4、@JsonIgnore这个是在转换成json是忽略该属性,而@JsonIgnoreProperties(value={"acctUsers", "acctAuthorities"})则是忽略acctRoles里面的acctUsers和acctAuthorites属性。
6、创建Dao层
6.1Dao接口
Dao层和Service层我们肯定采用的是面相接口编程的思想,所以,我们先定义一个通用的Dao接口,GenericDao.java
- package org.andy.work.dao;
- import java.io.Serializable;
- import java.util.List;
- /**
- * 创建时间:2015-2-6 下午2:26:42
- *
- * @author andy
- * @version 2.2
- *
- * Dao通用接口
- */
- interface GenericDao<T, PK extends Serializable> {
- T load(PK id);
- T get(PK id);
- List<T> findAll();
- void persist(T entity);
- PK save(T entity);
- void saveOrUpdate(T entity);
- void delete(PK id);
- void flush();
- }
在定义具体的UserDao.java接口
- package org.andy.work.dao;
- import org.andy.work.entity.AcctUser;
- /**
- * 创建时间:2015-2-6 下午2:43:50
- *
- * @author andy
- * @version 2.2
- *
- * 用户Dao接口
- */
- public interface UserDao extends GenericDao<AcctUser, String> {
- }
6.2、Dao层实现类
我们需要将Dao层的实现类注入为bean,所以需要添加@Repository注解,UserDaoImpl如下:
- package org.andy.work.dao.impl;
- import java.util.List;
- import org.andy.work.dao.UserDao;
- import org.andy.work.entity.AcctUser;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Repository;
- /**
- * 创建时间:2015-2-6 下午2:45:14
- *
- * @author andy
- * @version 2.2
- */
- @Repository("userDao")
- public class UserDaoImpl implements UserDao {
- @Autowired
- private SessionFactory sessionFactory;
- private Session getCurrentSession() {
- return this.sessionFactory.getCurrentSession();
- }
- @Override
- public AcctUser load(String id) {
- return (AcctUser) this.getCurrentSession().load(AcctUser.class, id);
- }
- @Override
- public AcctUser get(String id) {
- return (AcctUser) this.getCurrentSession().get(AcctUser.class, id);
- }
- @SuppressWarnings("unchecked")
- @Override
- public List<AcctUser> findAll() {
- List<AcctUser> acctUsers = this.getCurrentSession().createQuery("from AcctUser").setCacheable(true).list();
- return acctUsers;
- }
- @Override
- public void persist(AcctUser entity) {
- this.getCurrentSession().persist(entity);
- }
- @Override
- public String save(AcctUser entity) {
- return (String) this.getCurrentSession().save(entity);
- }
- @Override
- public void saveOrUpdate(AcctUser entity) {
- this.getCurrentSession().saveOrUpdate(entity);
- }
- @Override
- public void delete(String id) {
- AcctUser entity = this.load(id);
- this.getCurrentSession().delete(entity);
- }
- @Override
- public void flush() {
- this.getCurrentSession().flush();
- }
- }
7、创建Service层
7.1、Service层接口
- package org.andy.work.service;
- import java.util.List;
- import org.andy.work.entity.AcctUser;
- /**
- * 创建时间:2015-2-6 下午3:18:57
- *
- * @author andy
- * @version 2.2
- * userService接口
- */
- public interface UserService {
- AcctUser load(String id);
- AcctUser get(String id);
- List<AcctUser> findAll();
- void persist(AcctUser entity);
- String save(AcctUser entity);
- void saveOrUpdate(AcctUser entity);
- void delete(String id);
- void flush();
- }
7.2、service层实现类
UserServiceImpl就需要注入上面定义的Dao层bean。
- package org.andy.work.service.impl;
- import java.util.List;
- import org.andy.work.dao.UserDao;
- import org.andy.work.entity.AcctUser;
- import org.andy.work.service.UserService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- /**
- * 创建时间:2015-2-6 下午3:24:16
- *
- * @author andy
- * @version 2.2 UserService 的实现
- */
- @Service("userService")
- public class UserServiceImpl implements UserService {
- @Autowired
- private UserDao userDao;
- @Override
- public AcctUser load(String id) {
- return userDao.load(id);
- }
- @Override
- public AcctUser get(String id) {
- return userDao.get(id);
- }
- @Override
- public List<AcctUser> findAll() {
- return userDao.findAll();
- }
- @Override
- public void persist(AcctUser entity) {
- userDao.persist(entity);
- }
- @Override
- public String save(AcctUser entity) {
- return userDao.save(entity);
- }
- @Override
- public void saveOrUpdate(AcctUser entity) {
- userDao.saveOrUpdate(entity);
- }
- @Override
- public void delete(String id) {
- userDao.delete(id);
- }
- @Override
- public void flush() {
- userDao.flush();
- }
- }
8、测试Spring和Hibernate的整合
我们可以在src/test/java编写测试类,测试上面的配置,如果测试成功已经基本大功告成。
- package org.andy.work.service;
- import java.util.Date;
- import java.util.List;
- import java.util.UUID;
- import org.andy.work.entity.AcctUser;
- import org.apache.log4j.Logger;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.test.context.ContextConfiguration;
- import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
- import com.alibaba.fastjson.JSON;
- /**
- * 创建时间:2015-2-6 下午3:31:07
- *
- * @author andy
- * @version 2.2
- */
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(locations = { "classpath:spring.xml",
- "classpath:spring-hibernate.xml" })
- public class TestUserService {
- private static final Logger LOGGER = Logger
- .getLogger(TestUserService.class);
- @Autowired
- private UserService userService;
- @Test
- public void save() {
- AcctUser acctUser = new AcctUser();
- acctUser.setId(UUID.randomUUID().toString());
- acctUser.setNickName("andy");
- acctUser.setRegisterTime(new Date());
- acctUser.setTelephone("13022221111");
- String id = userService.save(acctUser);
- LOGGER.info(JSON.toJSONString(id));
- }
- }
9、引入SpringMVC
添加spring-mvc.xml文件
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-4.1.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
- <!-- 自动扫描@Controller注入为bean -->
- <context:component-scan base-package="org.andy.work.controller" />
- <!-- 以下为SpringMVC配置 -->
- <mvc:annotation-driven>
- <!-- 返回json数据,@response使用 -->
- <mvc:message-converters register-defaults="true">
- <bean
- class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
- <property name="supportedMediaTypes">
- <list>
- <value>text/html;charset=UTF-8</value>
- <value>application/json;charset=UTF-8</value>
- </list>
- </property>
- </bean>
- </mvc:message-converters>
- </mvc:annotation-driven>
- <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
- <bean
- class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="viewClass"
- value="org.springframework.web.servlet.view.JstlView" />
- <property name="prefix" value="/WEB-INF/views" />
- <property name="suffix" value=".jsp" />
- </bean>
- </beans>
上面配置了包扫描Controller,将@Controller注入为spring的bean。以及springmvc的json处理,和视图层的配置。
10、配置web.xml容器
web容器是web项目的大脑,所以web容器,首先需要引入spring,让spring管理各个框架,并将其注入为bean。然后配置控制层的filter信息。并且配置了springmvc拦截的url为以.hmls结尾的请求。
web.xml文件如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
- id="WebApp_ID" version="2.5">
- <display-name>springmvc_demo</display-name>
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:spring.xml,classpath:spring-hibernate.xml</param-value>
- </context-param>
- <filter>
- <filter-name>encodingFilter</filter-name>
- <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>utf-8</param-value>
- </init-param>
- <init-param>
- <param-name>forceEncoding</param-name>
- <param-value>true</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>encodingFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <!-- openSessionInView配置 作用是延迟session关闭到view层 -->
- <filter>
- <filter-name>openSessionInViewFilter</filter-name>
- <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
- <init-param>
- <param-name>singleSession</param-name>
- <param-value>true</param-value>
- </init-param>
- </filter>
- <!-- 监听servletContext,启动contextConfigLocation中的spring配置信息 -->
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <!-- 防止spring内存溢出监听器 -->
- <listener>
- <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
- </listener>
- <servlet>
- <description>spring mvc servlet</description>
- <servlet-name>rest</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <!-- 此处配置的是SpringMVC的配置文件 -->
- <param-value>classpath:spring-mvc.xml</param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>rest</servlet-name>
- <url-pattern>*.htmls</url-pattern>
- </servlet-mapping>
- <filter-mapping>
- <filter-name>openSessionInViewFilter</filter-name>
- <url-pattern>*.htmls</url-pattern>
- </filter-mapping>
- <!-- 配置session超时时间,单位分钟 -->
- <session-config>
- <session-timeout>30</session-timeout>
- </session-config>
- <welcome-file-list>
- <welcome-file>/index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
11、创建控制层Controller
控制层UserController
- package org.andy.work.controller;
- import java.util.List;
- import org.andy.work.entity.AcctUser;
- import org.andy.work.service.UserService;
- import org.apache.log4j.Logger;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.ModelMap;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
- /**
- * 创建时间:2015-2-7 上午11:49:00
- * @author andy
- * @version 2.2
- * 描述: 用户Controller
- */
- @Controller
- @RequestMapping("/user")
- public class UserController {
- private static final Logger LOGGER = Logger.getLogger(UserController.class);
- @Autowired
- private UserService userService;
- @RequestMapping("/showInfo/{userId}")
- public String showUserInfo(ModelMap modelMap, @PathVariable String userId){
- LOGGER.info("查询用户:" + userId);
- AcctUser userInfo = userService.load(userId);
- modelMap.addAttribute("userInfo", userInfo);
- return "/user/showInfo";
- }
- @RequestMapping("/showInfos")
- public @ResponseBody List<AcctUser> showUserInfos(){
- LOGGER.info("查询用户全部用户");
- List<AcctUser> userInfos = userService.findAll();
- return userInfos;
- }
- }
12、创建视图层
在src/main/webapp/WEB-INF/views下 创建user/showInfo.jsp
- <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
- <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
- <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme() + "://"
- + request.getServerName() + ":" + request.getServerPort()
- + path + "/";
- %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <base href="<%=basePath%>" />
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
- <title>userInfo</title>
- </head>
- <body>
- 用户信息 昵称: ${userInfo.nickName} 用户id:${userInfo.id} 用户电话:${userInfo.telephone } 注册时间:
- <fmt:formatDate value="${userInfo.registerTime }" pattern="yyyy-MM-dd HH:mm:ss" />
- 角色:[
- <c:forEach items="${ userInfo.acctRoles}" var="role">
- ${role.name } 权限[
- <c:forEach items="${ role.acctAuthorities}" var="authority">
- ${authority.name }
- </c:forEach> ]
- </c:forEach>
- ]
- <br /> ajax显示全部用户信息:
- <div id="show_all_user"></div>
- </body>
- <script type="text/javascript">
- $.ajax({
- type : "get",
- url : "user/showInfos.htmls",
- dataType : "json",
- success : function(data) {
- $(data).each(
- function(i, user) {
- var p = "<p>昵称:" + user.nickName + " 电话:"
- + user.telephone + " 注册时间:"
- + user.registerTime + " id:" + user.id +
- "</p>";
- $("#show_all_user").append(p);
- });
- },
- async : true
- });
- </script>
- </html>
13、部署服务器测试
使用Maven打包部署:clean compile package
部署到tomcat,测试
主要测试上面的 http://localhost:8080/springmvc_hibernate_demo/user/showInfo/6e5afb1d-50e1-45fe-b6fe-b9e399415387.htmls
和http://localhost:8080/springmvc_hibernate_demo/user/showInfos.htmls (json数据返回)
上面视图层就包含了这两条url请求的测试:
ok,到此Spring+SpringMVC+Hibernate搭建完毕。
相关推荐
** Maven 搭建 SpringMVC + Hibernate 框架详解 ** 在现代软件开发中,Maven 是一个强大的项目管理工具,它帮助开发者管理构建过程、依赖关系和项目信息。SpringMVC 和 Hibernate 则是两个流行的技术,分别用于构建...
下面将详细解释这三个框架的集成以及 EasyUI 和 Maven 在项目搭建中的作用。 **Spring 框架** Spring 是一个全面的企业级应用框架,它通过提供 DI 和 AOP 实现了松耦合,使得代码更易于测试和维护。DI 允许外部容器...
**SSH整合详解** SSH,即Spring、SpringMVC和Hibernate,是Java开发中常见的三大框架组合,用于构建高效、模块化的Web应用。本教程将详细讲解如何使用Maven来整合这三个框架,创建一个完整的SSH Demo。 ### Maven...
**Spring MVC + Hibernate Maven 空框架详解** Spring MVC 和 Hibernate 是两个在 Java Web 开发中广泛使用的开源框架。Spring MVC 作为 Spring 框架的一部分,主要用于构建 MVC(Model-View-Controller)架构的 ...
在“maven(springmvc+spring+hibernate)”的描述中提到了Hibernate,虽然不是SSM中的组成部分,但它是另一种流行的ORM(对象关系映射)框架,可以替代MyBatis。Hibernate简化了与数据库的交互,通过对象来操作数据,...
**SpringMVC+Hibernate Maven 增删改查与分页实现详解** SpringMVC 和 Hibernate 是两个在 Java Web 开发中广泛使用的框架。SpringMVC 作为 Spring 框架的一部分,负责处理请求和响应,提供了一种模型-视图-控制器...
《基于SpringMvc+Hibernate的问题管理系统实现详解》 在IT领域,高效的问题管理是任何软件开发团队不可或缺的一部分。本文将深入探讨如何使用SpringMvc和Hibernate这两个强大的框架,构建一个功能完善的问题管理...
本文将深入探讨一个基于Spring MVC、Spring和Hibernate框架的Maven项目,该系统专注于学生管理,旨在帮助初学者理解并掌握Maven项目结构以及这三个框架的集成应用。 首先,Spring MVC作为Spring框架的一部分,是...
**SpringMVC+Spring3.2+Hibernate4整合详解** 在现代Java开发中,Spring框架以其模块化、可扩展性和企业级应用支持而备受青睐。本篇将详细讲解如何将SpringMVC、Spring3.2和Hibernate4进行整合,构建一个高效、灵活...
Maven 和 SpringMVC 环境搭建详解 Maven 是一个流行的Java项目管理和构建工具,它可以自动管理项目的依赖关系,简化项目的构建和管理过程。在本文中,我们将详细介绍如何使用 Maven 搭建 SpringMVC 环境,并且详细...
**SpringBoot/SpringMVC/Hibernate整合源码详解** 在Java Web开发中,Spring Boot、Spring MVC和Hibernate是三个非常重要的框架。Spring Boot简化了Spring应用程序的初始设置和配置,Spring MVC提供了处理HTTP请求...
- **Eclipse IDE**: 使用Maven项目管理,有助于模块化开发,简化依赖管理。 - **代码生成**: 可通过界面配置快速生成代码,支持单表、一对多、树结构等多种生成方式。 #### 二、技术栈选型 - **后端** - **服务...
本项目涉及的是四个流行的Java Web框架——Maven、SpringMVC、MyBatis和Hibernate——之间的两两整合。下面将详细阐述这些框架的特点以及整合过程中的关键知识点。 1. Maven: Maven是一个项目管理和综合工具,它...
### SpringMVC+Shiro权限管理系统详解 #### 权限管理概述 权限管理在软件开发中扮演着至关重要的角色,特别是在涉及多用户交互的应用场景下。通过合理的权限控制,可以确保不同用户仅能访问和操作他们被授权的功能...
【Hibernate详解】: Hibernate是一个强大的ORM框架,它允许开发者使用面向对象的方式来操作数据库,减少了数据库操作的复杂性。Hibernate通过映射机制将Java对象与数据库表关联,支持CRUD(创建、读取、更新、删除...
- **配置项目**:创建Maven或Gradle项目,引入SpringMVC、Hibernate、MySQL驱动等必要依赖。 - **配置SpringMVC**:编写`web.xml`,设置DispatcherServlet,配置SpringMVC的核心配置文件路径。 - **配置Hibernate**...
《构建企业级Web应用:Spring、SpringMVC、Hibernate、Shiro、Maven与EasyUI集成详解》 在现代企业级Web开发中,一个高效、稳定的框架组合是至关重要的。"tianyu"项目整合了Spring、SpringMVC、Hibernate、Shiro、...
在本项目中,我们主要探讨的是如何搭建一个基于Spring、SpringMVC和MyBatis的简单Web应用程序框架,也就是SSM框架。这是一个经典的Java后端开发组合,常用于构建高效、可扩展的企业级应用。首先,让我们逐一了解这三...