【maven + hibernate(注解) +spring +springMVC】 使用maven搭建项目

  1. 云栖社区>
  2. 博客>
  3. 正文

【maven + hibernate(注解) +spring +springMVC】 使用maven搭建项目

angel挤一挤 2016-06-22 13:41:00 浏览1525
展开阅读全文

研究,百度,查资料+好友帮助,使用MyEcplise2015工具,通过maven搭建hibernate+springMVC+spring的项目,数据库采用MySql5.5 不过使用的版本会在项目搭建过程中介绍。

大概就是下面的几个步骤:

1. 设计数据库,得到数据库

2.使用maven搭建项目,导入包的依赖

3.引入spring的配置信息,放在资源文件中

4.引入Log4j日志文件配置

5.配置hibernate

6.配置ehcache.xml

7.使用hibernate  tools生成实体

8.创建Dao层、service层

9.配置spring-mvc.xml

10.配置web.xml容器

11.创建Controller层

12.创建view层

13.打包,部署,运行项目

 

1.设计数据库,并创建数据库

1.1 使用powerDesigner,设计数据表,生成cdm

设计三个数据表分别为角色表,权限表以及用户表,三张表之间分别是多对多的关系。三个实体的主键均使用UUID,因此设计主键长度为varchar(36)

 

1.2 继续生成pdm

由于三张表之间是多对多,生成两张中间表,分别是角色权限表和用户角色表

 

 这个怎么用就不介绍了,总而言之,最后生成SQL语句,然后在MySQL运行,创建一个新的数据库,生成如下的数据库:

2.创建maven项目,导入项目所需依赖架包

2.1创建maven项目

 

新创建成的maven项目结构如下,我们将这个项目结构完善

首先将这个项目转化为web项目,项目右键-->properties,在设置过程中,注意Web版本与jave版本的相互支持

项目转成web项目之后,会生成下面的这个目录

我们要做的就是把这个WebRoot目录下的东西放到src下的webapp下,让它符合maven项目的结构标准.然后,删除WebRoot目录即可。

2.2 调一下项目中的小错误

首先双击pom.xml文件,设置web版本

 

双击Inxde.jsp文件,发现没有httpservlet架包,那我们就进入build path,给项目添加所支持架包

 

既然改到这里了,我们的JRE版本太低了,把它替换成高的版本,顺便把J2EE的架包也搞进来,以备不时之需

搞进来J2EE的lib

搞进来JRE的lib

此时,小错误全部消除完成,现在的项目结构如下所示:

 

2.3 现在配置pom.xml。导入项目依赖架包

  1 <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/xsd/maven-4.0.0.xsd">
  2   <modelVersion>4.0.0</modelVersion>
  3   <groupId>com.it</groupId>
  4   <artifactId>mySecond</artifactId>
  5   <version>0.0.1-SNAPSHOT</version>
  6   <packaging>war</packaging>
  7   <build>
  8       <plugins>
  9           <plugin>
 10               <artifactId>maven-war-plugin</artifactId>
 11               <configuration>
 12                   <version>3.0</version>
 13               </configuration>
 14           </plugin>
 15       </plugins>
 16   </build>
 17   
 18       <name>myAgen</name>
 19     <url>http://maven.apache.org</url>
 20 
 21     <properties>
 22         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 23         <spring.version>4.1.4.RELEASE</spring.version>
 24         <hibernate.version>4.3.8.Final</hibernate.version>
 25         <jackson.version>2.5.0</jackson.version>
 26         
 27     </properties>
 28 
 29     <dependencies>
 30 
 31         <!-- junit -->
 32         <dependency>
 33             <groupId>junit</groupId>
 34             <artifactId>junit</artifactId>
 35             <version>4.12</version>
 36             <scope>test</scope>
 37         </dependency>
 38 
 39         <!-- spring -->
 40         <dependency>
 41             <groupId>org.springframework</groupId>
 42             <artifactId>spring-core</artifactId>
 43             <version>${spring.version}</version>
 44         </dependency>
 45 
 46         <dependency>
 47             <groupId>org.springframework</groupId>
 48             <artifactId>spring-beans</artifactId>
 49             <version>${spring.version}</version>
 50         </dependency>
 51 
 52         <dependency>
 53             <groupId>org.springframework</groupId>
 54             <artifactId>spring-context</artifactId>
 55             <version>${spring.version}</version>
 56         </dependency>
 57 
 58         <dependency>
 59             <groupId>org.springframework</groupId>
 60             <artifactId>spring-tx</artifactId>
 61             <version>${spring.version}</version>
 62         </dependency>
 63 
 64         <dependency>
 65             <groupId>org.springframework</groupId>
 66             <artifactId>spring-web</artifactId>
 67             <version>${spring.version}</version>
 68         </dependency>
 69 
 70         <dependency>
 71             <groupId>org.springframework</groupId>
 72             <artifactId>spring-test</artifactId>
 73             <version>${spring.version}</version>
 74             <scope>test</scope>
 75         </dependency>
 76 
 77         <!-- 使用SpringMVC需配置 -->
 78         <dependency>
 79             <groupId>org.springframework</groupId>
 80             <artifactId>spring-webmvc</artifactId>
 81             <version>${spring.version}</version>
 82         </dependency>
 83         <!-- spring  cglib 代理 -->
 84         <dependency>
 85             <groupId>cglib</groupId>
 86             <artifactId>cglib</artifactId>
 87             <version>2.2.2</version>
 88         </dependency>
 89         <!-- 关系型数据库整合时需配置 如hibernate jpa等 -->
 90         <dependency>
 91             <groupId>org.springframework</groupId>
 92             <artifactId>spring-orm</artifactId>
 93             <version>${spring.version}</version>
 94         </dependency>
 95 
 96         <!-- hibernate -->
 97         <dependency>
 98             <groupId>org.hibernate</groupId>
 99             <artifactId>hibernate-core</artifactId>
100             <version>${hibernate.version}</version>
101         </dependency>
102 
103         <dependency>
104             <groupId>org.hibernate</groupId>
105             <artifactId>hibernate-ehcache</artifactId>
106             <version>${hibernate.version}</version>
107         </dependency>
108 
109         <!-- 二级缓存ehcache -->
110         <dependency>
111             <groupId>net.sf.ehcache</groupId>
112             <artifactId>ehcache</artifactId>
113             <version>2.9.0</version>
114         </dependency>
115 
116         <!-- log4j -->
117         <dependency>
118             <groupId>log4j</groupId>
119             <artifactId>log4j</artifactId>
120             <version>1.2.17</version>
121         </dependency>
122 
123         <!-- mysql连接 -->
124         <dependency>
125             <groupId>mysql</groupId>
126             <artifactId>mysql-connector-java</artifactId>
127             <version>5.1.34</version>
128         </dependency>
129 
130         <!-- c3p0数据源 -->
131         <dependency>
132             <groupId>com.mchange</groupId>
133             <artifactId>c3p0</artifactId>
134             <version>0.9.5-pre10</version>
135         </dependency>
136 
137         <!-- json -->
138         <dependency>
139             <groupId>com.alibaba</groupId>
140             <artifactId>fastjson</artifactId>
141             <version>1.2.3</version>
142         </dependency>
143 
144         <dependency>
145             <groupId>com.fasterxml.jackson.core</groupId>
146             <artifactId>jackson-annotations</artifactId>
147             <version>${jackson.version}</version>
148         </dependency>
149 
150         <dependency>
151             <groupId>com.fasterxml.jackson.core</groupId>
152             <artifactId>jackson-core</artifactId>
153             <version>${jackson.version}</version>
154         </dependency>
155 
156         <dependency>
157             <groupId>com.fasterxml.jackson.core</groupId>
158             <artifactId>jackson-databind</artifactId>
159             <version>${jackson.version}</version>
160         </dependency>
161 
162         <!-- aop -->
163         <dependency>
164             <groupId>org.aspectj</groupId>
165             <artifactId>aspectjweaver</artifactId>
166             <version>1.8.4</version>
167         </dependency>
168 
169         <!-- servlet -->
170         <dependency>
171             <groupId>javax.servlet</groupId>
172             <artifactId>servlet-api</artifactId>
173             <version>3.0-alpha-1</version>
174             <scope>provided</scope>
175         </dependency>
176 
177         <dependency>
178             <groupId>javax.servlet</groupId>
179             <artifactId>jstl</artifactId>
180             <version>1.2</version>
181         </dependency>
182 
183     </dependencies>
184 </project>    
View Code

3.引入spring的配置信息,放在资源文件中

路径下创建config.properties文件,这里面存放的就是一堆的变量,有关hibernate配置的变量

 

 1 #application configs
 2 
 3 #jdbc c3p0 config
 4 jdbc.driver = com.mysql.jdbc.Driver
 5 jdbc.url = jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=utf-8
 6 jdbc.username = root
 7 jdbc.password = root
 8 
 9 #hibernate config
10 hibernate.dialect = org.hibernate.dialect.MySQLDialect
11 hibernate.show_sql = true
12 hibernate.format_sql = false
13 hibernate.hbm2ddl.auto = update
14 hibernate.cache.use_second_level_cache = true
15 hibernate.cache.use_query_cache = true
16 hibernate.cache.region.factory_class = org.hibernate.cache.ehcache.EhCacheRegionFactory
17 hibernate.cache.provider_configuration_file_resource_path =ehcache.xml
View Code

 

 

 

 

4.引入Log4j日志文件配置

下创建log4j.properties,

 

 1 ### set log levels ###
 2 log4j.rootLogger = INFO , C , D , E 
 3 
 4 ### console ###
 5 log4j.appender.C = org.apache.log4j.ConsoleAppender
 6 log4j.appender.C.Target = System.out
 7 log4j.appender.C.layout = org.apache.log4j.PatternLayout
 8 log4j.appender.C.layout.ConversionPattern = [springmvc_hibernate_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
 9 
10 ### log file ###
11 log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
12 log4j.appender.D.File = ../logs/springmvc_hibernate_demo.log
13 log4j.appender.D.Append = true
14 log4j.appender.D.Threshold = INFO 
15 log4j.appender.D.layout = org.apache.log4j.PatternLayout
16 log4j.appender.D.layout.ConversionPattern = [springmvc_hibernate_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
17 
18 ### exception ###
19 log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
20 log4j.appender.E.File = ../logs/springmvc_hibernate_demo_error.log 
21 log4j.appender.E.Append = true
22 log4j.appender.E.Threshold = ERROR 
23 log4j.appender.E.layout = org.apache.log4j.PatternLayout
24 log4j.appender.E.layout.ConversionPattern =[sspringmvc_hibernate_demo][%p] [%-d{yyyy-MM-dd HH\:mm\:ss}] %C.%M(%L) | %m%n
View Code

 

 

 

 

5.配置hibernate

下创建spring-hibernate.xml,其中配置了数据源dataSource,配置sessionFactory,配置事务管理器。【如果需要连接多干服务器上的多个数据库,那就可以再多配一份同样的dataSource,sessionFacrory,事务管理器,在注入的时候,在Controller中,@Resource(注明是哪个sessionFactory即可)这里可能有误,之后再说】

 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:tx="http://www.springframework.org/schema/tx"
 5     xmlns:aop="http://www.springframework.org/schema/aop"
 6     xmlns:context="http://www.springframework.org/schema/context"
 7     xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
 8         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
 9         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
10         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
11         
12     <!-- 自动扫描@Controller注入为bean -->
13     <context:property-placeholder location="classpath:config.properties"/>
14     
15         
16     <!-- 配置数据源 c3p0 -->
17     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
18         destroy-method="close">
19         <property name="driverClass" value="${jdbc.driver}" />
20         <property name="jdbcUrl" value="${jdbc.url}" />
21         <property name="user" value="${jdbc.username}" />
22         <property name="password" value="${jdbc.password}" />
23 
24         <!-- 请求超时时间 -->
25         <property name="checkoutTimeout" value="30000" />
26         <!-- 每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 -->
27         <property name="idleConnectionTestPeriod" value="30" />
28         <!-- 连接数据库连接池最大空闲时间 -->
29         <property name="maxIdleTime" value="30" />
30         <!-- 连接池初始化连接数 -->
31         <property name="initialPoolSize" value="5" />
32         <property name="minPoolSize" value="5" />
33         <property name="maxPoolSize" value="20" />
34         <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 -->
35         <property name="acquireIncrement" value="5" />
36     </bean>
37 
38     <!-- 配置hibernate的SessionFactory -->
39     <bean id="sessionFactory"
40         class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
41         <!-- 注入数据源 相关信息看源码 -->
42         <property name="dataSource" ref="dataSource" />
43         <!-- hibernate配置信息 -->
44         <property name="hibernateProperties">
45             <props>
46                 <prop key="hibernate.dialect">${hibernate.dialect}</prop>
47                 <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
48                 <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
49                 <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
50 
51                 <!-- 开启二级缓存 ehcache -->
52                 <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
53                 <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
54                 <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>
55                 <prop key="hibernate.cache.provider_configuration_file_resource_path">${hibernate.cache.provider_configuration_file_resource_path}
56                 </prop>
57             </props>
58         </property>
59         <!-- 扫描hibernate注解配置的entity -->
60         <property name="packagesToScan" value="com.it.entity" />
61     </bean>
62 
63     <!-- 配置事务管理器 -->
64     <bean id="transactionManager"
65         class="org.springframework.orm.hibernate4.HibernateTransactionManager">
66         <property name="sessionFactory" ref="sessionFactory" />
67     </bean>
68 
69     
70     
71     
72     
73 
74 </beans>
View Code

 

 

 

 

6.配置ehcache.xml

下创建ehcache.xml,配置的二级缓存

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
 3     <diskStore path="D:/ehcache" />
 4     <!-- DefaultCache setting. -->
 5      <defaultCache
 6             maxElementsInMemory="1000"
 7             eternal="false"
 8             timeToIdleSeconds="120"
 9             timeToLiveSeconds="120"
10             maxElementsOnDisk="1000000"
11             overflowToDisk="true" 
12             memoryStoreEvictionPolicy="LRU">
13             
14     </defaultCache>
15 
16     <!-- Special objects setting. -->
17 
18     <cache 
19          name="org.andy.work.entity.AcctUser"
20          maxElementsInMemory="2"
21          memoryStoreEvictionPolicy="LRU" 
22          eternal="true" 
23          diskPersistent="false"
24          overflowToDisk="false" 
25          maxElementsOnDisk="1000000" /> 
26 
27 
28 
29 </ehcache>
View Code

 

 

7.使用hibernate  tools生成实体

在MyEcplise右上角,点击【如果没有,就点击MyEcplise Java Enterprise 左边的小图标】MyEcplise  Hibernate,进入

 

在这里,New一个新的连接。连接到指定的数据库上

编辑新的连接,下面的这些,必须完全一致,除了账号密码和驱动的路径,但是选择了驱动之后,Driver ClassName必须得是com.mysql.jdbc.Driver【如果是MySQL数据库的话】.

编辑完成之后可以Test Driver一下看看是否可以连接成功。

连接成功之后如下,我们就开始选择所有数据表,点击hibernate反转,生成entity

但是此刻发现我们要选择的folder中不能指定到我们的项目中,我们的项目没有被识别出来。

因此需要点击MyEcplise Jave Enterprise,回去设置我们的项目,让项目支持hibernate,或者说让项目变成hibernate项目

右键项目 --->properties--->Project Facets

 

 完了之后会有两个自动生成的文件,看看是否需要留着,或者删除

 然后再回到hibernate tools下面

这次就可以看到本项目了

因为要使用注解的形式,所以,按照下面的选择,

主键使用UUID,注意hibernate的版本的问题,需要注意选择的主键生成策略

 包下生成的实体如下:

 下面贴出来生成实体的代码:

Authority.java

 1 package com.it.entity;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 import javax.persistence.CascadeType;
 6 import javax.persistence.Column;
 7 import javax.persistence.Entity;
 8 import javax.persistence.FetchType;
 9 import javax.persistence.GeneratedValue;
10 import javax.persistence.Id;
11 import javax.persistence.ManyToMany;
12 import javax.persistence.Table;
13 import org.hibernate.annotations.GenericGenerator;
14 
15 /**
16  * Authority entity. @author MyEclipse Persistence Tools
17  */
18 @Entity
19 @Table(name = "authority", catalog = "testdb")
20 public class Authority implements java.io.Serializable {
21 
22     // Fields
23 
24     private String authorityId;
25     private String authorityName;
26     private Set<Role> roles = new HashSet<Role>(0);
27 
28     // Constructors
29 
30     /** default constructor */
31     public Authority() {
32     }
33 
34     /** full constructor */
35     public Authority(String authorityName, Set<Role> roles) {
36         this.authorityName = authorityName;
37         this.roles = roles;
38     }
39 
40     // Property accessors
41     @GenericGenerator(name = "generator", strategy = "uuid.hex")
42     @Id
43     @GeneratedValue(generator = "generator")
44     @Column(name = "authorityId", unique = true, nullable = false, length = 36)
45     public String getAuthorityId() {
46         return this.authorityId;
47     }
48 
49     public void setAuthorityId(String authorityId) {
50         this.authorityId = authorityId;
51     }
52 
53     @Column(name = "authorityName", length = 50)
54     public String getAuthorityName() {
55         return this.authorityName;
56     }
57 
58     public void setAuthorityName(String authorityName) {
59         this.authorityName = authorityName;
60     }
61 
62     @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "authorities")
63     public Set<Role> getRoles() {
64         return this.roles;
65     }
66 
67     public void setRoles(Set<Role> roles) {
68         this.roles = roles;
69     }
70 
71 }
View Code

Myuser.java

  1 package com.it.entity;
  2 
  3 import java.sql.Timestamp;
  4 import java.util.HashSet;
  5 import java.util.Set;
  6 import javax.persistence.CascadeType;
  7 import javax.persistence.Column;
  8 import javax.persistence.Entity;
  9 import javax.persistence.FetchType;
 10 import javax.persistence.GeneratedValue;
 11 import javax.persistence.Id;
 12 import javax.persistence.ManyToMany;
 13 import javax.persistence.Table;
 14 import org.hibernate.annotations.GenericGenerator;
 15 
 16 /**
 17  * Myuser entity. @author MyEclipse Persistence Tools
 18  */
 19 @Entity
 20 @Table(name = "myuser", catalog = "testdb")
 21 public class Myuser implements java.io.Serializable {
 22 
 23     // Fields
 24 
 25     private String myUserId;
 26     private String myUserName;
 27     private String myUserPhone;
 28     private Timestamp myUserTime;
 29     private Set<Role> roles = new HashSet<Role>(0);
 30 
 31     // Constructors
 32 
 33     /** default constructor */
 34     public Myuser() {
 35     }
 36 
 37     /** minimal constructor */
 38     public Myuser(Timestamp myUserTime) {
 39         this.myUserTime = myUserTime;
 40     }
 41 
 42     /** full constructor */
 43     public Myuser(String myUserName, String myUserPhone, Timestamp myUserTime,
 44             Set<Role> roles) {
 45         this.myUserName = myUserName;
 46         this.myUserPhone = myUserPhone;
 47         this.myUserTime = myUserTime;
 48         this.roles = roles;
 49     }
 50 
 51     // Property accessors
 52     @GenericGenerator(name = "generator", strategy = "uuid.hex")
 53     @Id
 54     @GeneratedValue(generator = "generator")
 55     @Column(name = "myUserId", unique = true, nullable = false, length = 36)
 56     public String getMyUserId() {
 57         return this.myUserId;
 58     }
 59 
 60     public void setMyUserId(String myUserId) {
 61         this.myUserId = myUserId;
 62     }
 63 
 64     @Column(name = "myUserName", length = 20)
 65     public String getMyUserName() {
 66         return this.myUserName;
 67     }
 68 
 69     public void setMyUserName(String myUserName) {
 70         this.myUserName = myUserName;
 71     }
 72 
 73     @Column(name = "myUserPhone", length = 11)
 74     public String getMyUserPhone() {
 75         return this.myUserPhone;
 76     }
 77 
 78     public void setMyUserPhone(String myUserPhone) {
 79         this.myUserPhone = myUserPhone;
 80     }
 81 
 82     @Column(name = "myUserTime", nullable = false, length = 19)
 83     public Timestamp getMyUserTime() {
 84         return this.myUserTime;
 85     }
 86 
 87     public void setMyUserTime(Timestamp myUserTime) {
 88         this.myUserTime = myUserTime;
 89     }
 90 
 91     @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "myusers")
 92     public Set<Role> getRoles() {
 93         return this.roles;
 94     }
 95 
 96     public void setRoles(Set<Role> roles) {
 97         this.roles = roles;
 98     }
 99 
100 }
View Code

Role.java

 1 package com.it.entity;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 import javax.persistence.CascadeType;
 6 import javax.persistence.Column;
 7 import javax.persistence.Entity;
 8 import javax.persistence.FetchType;
 9 import javax.persistence.GeneratedValue;
10 import javax.persistence.Id;
11 import javax.persistence.JoinColumn;
12 import javax.persistence.JoinTable;
13 import javax.persistence.ManyToMany;
14 import javax.persistence.Table;
15 import org.hibernate.annotations.GenericGenerator;
16 
17 /**
18  * Role entity. @author MyEclipse Persistence Tools
19  */
20 @Entity
21 @Table(name = "role", catalog = "testdb")
22 public class Role implements java.io.Serializable {
23 
24     // Fields
25 
26     private String roleId;
27     private String roleName;
28     private Set<Myuser> myusers = new HashSet<Myuser>(0);
29     private Set<Authority> authorities = new HashSet<Authority>(0);
30 
31     // Constructors
32 
33     /** default constructor */
34     public Role() {
35     }
36 
37     /** full constructor */
38     public Role(String roleName, Set<Myuser> myusers, Set<Authority> authorities) {
39         this.roleName = roleName;
40         this.myusers = myusers;
41         this.authorities = authorities;
42     }
43 
44     // Property accessors
45     @GenericGenerator(name = "generator", strategy = "uuid.hex")
46     @Id
47     @GeneratedValue(generator = "generator")
48     @Column(name = "roleId", unique = true, nullable = false, length = 36)
49     public String getRoleId() {
50         return this.roleId;
51     }
52 
53     public void setRoleId(String roleId) {
54         this.roleId = roleId;
55     }
56 
57     @Column(name = "roleName", length = 20)
58     public String getRoleName() {
59         return this.roleName;
60     }
61 
62     public void setRoleName(String roleName) {
63         this.roleName = roleName;
64     }
65 
66     @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
67     @JoinTable(name = "userrole", catalog = "testdb", joinColumns = { @JoinColumn(name = "roleId", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "myUserId", nullable = false, updatable = false) })
68     public Set<Myuser> getMyusers() {
69         return this.myusers;
70     }
71 
72     public void setMyusers(Set<Myuser> myusers) {
73         this.myusers = myusers;
74     }
75 
76     @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
77     @JoinTable(name = "roleauthor", catalog = "testdb", joinColumns = { @JoinColumn(name = "roleId", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "authorityId", nullable = false, updatable = false) })
78     public Set<Authority> getAuthorities() {
79         return this.authorities;
80     }
81 
82     public void setAuthorities(Set<Authority> authorities) {
83         this.authorities = authorities;
84     }
85 
86 }
View Code

上面有几个需要注意的

 

     上面大多数都是Hibernate tools自动生成的,但是有几个需要手动添加:

              1、如果这个实体使用二级缓存的话,需要添加@cache注解;

              2、如果该实体里面还有集合元素(set, map,list),如果实体要采用二级缓存,那么这些集合元素必须也添加@cache注解

              3、@JsonIgnoreProperties注解是为了防止SpringMVC在json返回时产生循环输出使用,如果不配置的话就会出现json死循环(还有多对多,一对多的属性时)。

             4、@JsonIgnore这个是在转换成json是忽略该属性,而@JsonIgnoreProperties(value={"acctUsers", "acctAuthorities"})则是忽略acctRoles里面的acctUsers和acctAuthorites属性。

 

8.创建Dao层、service层

8.1 创建Dao层,面向接口的思想创建

8.1.1  先要创建一个基础Dao

 1 package com.it.dao;
 2 
 3 import java.io.Serializable;
 4 import java.util.List;
 5 
 6 public interface GenericDao<T, PK extends Serializable> {
 7     
 8     T load(PK id);
 9     
10     T get(PK id);
11     
12     List<T> findAll();
13     
14     void persist(T entity);
15     
16     PK save(T entity);
17     
18     void saveOrUpdate(T entity);
19     
20     void delete(PK id);
21     
22     void flush();
23 }
View Code

8.1.2 再定义具体的接口,继承基础的Dao

 1 package com.it.dao;
 2 
 3 import com.it.entity.Myuser;
 4 
 5 /**
 6  * MyUser的Dao
 7  * @author Administrator
 8  *
 9  */
10 public interface MyUserDao extends GenericDao<Myuser, String> {
11     
12 }
View Code

8.1.3 接着定义具体的DaoImpl的实现类

 1 package com.it.dao.Impl;
 2 
 3 import java.util.List;
 4 
 5 
 6 import org.hibernate.Session;
 7 import org.hibernate.SessionFactory;
 8 import org.springframework.beans.factory.annotation.Autowired;
 9 import org.springframework.stereotype.Repository;
10 
11 import com.it.dao.MyUserDao;
12 import com.it.entity.Myuser;
13 
14 
15 @Repository("myUserDao")
16 public class MyUserDaoImpl implements MyUserDao {
17     
18     @Autowired
19     private SessionFactory sessionFactory;
20     
21     
22     private Session getCurrentSession() {
23         return this.sessionFactory.getCurrentSession();
24     }
25 
26     public Myuser load(String id) {
27         // TODO Auto-generated method stub
28         return (Myuser) this.getCurrentSession().load(Myuser.class, id);
29     }
30 
31     public Myuser get(String id) {
32         // TODO Auto-generated method stub
33         return (Myuser) this.getCurrentSession().get(Myuser.class, id);
34     }
35 
36     public List<Myuser> findAll() {
37         @SuppressWarnings("unchecked")
38         List<Myuser> allUser = this.getCurrentSession().createQuery("from Myuser").list();
39         return allUser;
40     }
41 
42     public void persist(Myuser entity) {
43         this.getCurrentSession().persist(entity);
44     }
45 
46     /**
47      * 可以选择手动控制事务的提交,也可以交给spring自动去提交
48      */
49     public String save(Myuser entity) {
50         // TODO Auto-generated method stub
51 //        Session session = sessionFactory.openSession();
52 //        session.getTransaction().begin();
53 //        session.;
54 //        session.getTransaction().commit();
55 //        session.flush();
56 //        session.close();
57         return (String) this.getCurrentSession().save(entity);
58     }
59 
60     public void saveOrUpdate(Myuser entity) {
61         // TODO Auto-generated method stub
62          this.getCurrentSession().saveOrUpdate(entity);
63     }
64 
65     public void delete(String id) {
66         // TODO Auto-generated method stub
67         Myuser myuser=this.load(id);
68         this.getCurrentSession().delete(myuser);
69     }
70 
71     public void flush() {
72         this.getCurrentSession().flush();
73     }
74 
75 }
View Code

8.2 创建service层,也是面向接口的思想创建

8.2.1 创建一个基础Service

 1 package com.it.service;
 2 
 3 import java.io.Serializable;
 4 import java.util.List;
 5 
 6 public interface GenericService<T, PK extends Serializable> {
 7     
 8     T load(PK id);
 9     
10     T get(PK id);
11     
12     List<T> findAll();
13     
14     void persist(T entity);
15     
16     PK save(T entity);
17     
18     void saveOrUpdate(T entity);
19     
20     void delete(PK id);
21     
22     void flush();
23 }
View Code

8.2.2 创建service继承基础的Service

1 package com.it.service;
2 
3 import com.it.entity.Myuser;
4 
5 public interface MyUserService extends GenericService<Myuser, String> {
6 
7 }
View Code

8.2.3 创建serviceImpl

 1 package com.it.service.Impl;
 2 
 3 import java.util.List;
 4 
 5 import javax.annotation.Resource;
 6 
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 import org.springframework.stereotype.Service;
 9 import org.springframework.transaction.annotation.Transactional;
10 
11 import com.it.dao.MyUserDao;
12 import com.it.entity.Myuser;
13 import com.it.service.GenericService;
14 import com.it.service.MyUserService;
15 
16 
17 @Service("myUserService")
18 @Transactional
19 public class MyUserServiceImpl implements MyUserService {
20     
21     @Resource(name = "myUserDao")
22     private MyUserDao myUserDao;
23     
24 
25     public Myuser load(String id) {
26         // TODO Auto-generated method stub
27         return myUserDao.load(id);
28     }
29 
30     public Myuser get(String id) {
31         // TODO Auto-generated method stub
32         return myUserDao.get(id);
33     }
34 
35     public List<Myuser> findAll() {
36         // TODO Auto-generated method stub
37         return myUserDao.findAll();
38     }
39 
40     public void persist(Myuser entity) {
41         // TODO Auto-generated method stub
42         myUserDao.persist(entity);
43     }
44     
45     public String save(Myuser entity) {
46         // TODO Auto-generated method stub
47         return myUserDao.save(entity);
48     }
49 
50     public void saveOrUpdate(Myuser entity) {
51         // TODO Auto-generated method stub
52         myUserDao.saveOrUpdate(entity);
53     }
54 
55     public void delete(String id) {
56         // TODO Auto-generated method stub
57         myUserDao.delete(id);
58     }
59 
60     public void flush() {
61         // TODO Auto-generated method stub
62         myUserDao.flush();
63     }
64 
65 }
View Code

 

9.配置spring-mvc.xml

spring-mvc.xml中配置了自动扫描Controller层注解+视图解析器

 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:mvc="http://www.springframework.org/schema/mvc"
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5     xmlns:p="http://www.springframework.org/schema/p"
 6     xmlns:context="http://www.springframework.org/schema/context"
 7     xmlns:tx="http://www.springframework.org/schema/tx"
 8     xmlns:aop="http://www.springframework.org/schema/aop"
 9     xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
10         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
11         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
12         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
13         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
14 
15     <!-- 自动扫描@Controller注入为bean -->
16     <context:component-scan base-package="com.it" >
17     
18     </context:component-scan>
19     <!-- 标明注解事务 -->
20     <tx:annotation-driven transaction-manager="transactionManager" />
21     
22     <!-- 以下为SpringMVC配置 -->
23     <mvc:annotation-driven>
24         <!-- 返回json数据,@response使用 -->
25         <mvc:message-converters register-defaults="true">
26             <bean
27                 class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
28                 <property name="supportedMediaTypes">
29                     <list>
30                         <value>text/html;charset=UTF-8</value>
31                         <value>application/json;charset=UTF-8</value>
32                     </list>
33                 </property>
34 
35             </bean>
36         </mvc:message-converters>
37     </mvc:annotation-driven>
38 
39     <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
40     <bean
41         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
42         <property name="viewClass"
43             value="org.springframework.web.servlet.view.JstlView" />
44         <property name="prefix" value="/WEB-INF/views" />
45         <property name="suffix" value=".jsp" />
46     </bean>
47     
48     <!-- 下面设置配置事物以及事务管理,是一种事务的处理方式,还可以有另一种 就是不写下面这一大块,直接在service层添加@Transactional
49     解释一下这两种的区别:
50     1.@Transactional  在serviceImpl层使用这个注解,表示默认的事务都是propagation="REQUIRED",这样不会有下面read-only这一项了,那么比如在查询的时候只要保证这个查询是在一个事务中,将结果查询出来,对这个对象进行修改,不用调用save等方法,事务会自动帮你进行持久化的操作,会将你这个操作保存在数据库中
51     2.使用下面的这两个事务管理,可以自己配置什么方法什么操作【insert、get】,可以自己设置事务的类型,也可以设置read-only。设置了read-only的话,在从数据库中查询出一条记录,对对象进行更改,那就必须调用save或者update方法才能进行保存
52     
53     
54      配置事务增强处理Bean,指定事务管理器   意思是这个id为transactionAdvice的事务(建议),他的事务管理者是上面指定的id为transactionManager的事务管理器
55     <tx:advice id="transactionAdvice" transaction-manager="transactionManager" >
56         配置详细事务处理语义
57         <tx:attributes>
58             在指定的如下的这些操作发生时,例如insert插入数据发生时,事务类型的request ,而get等操作,事务类型是supports,并且是只读
59             <tx:method name="insert*" propagation="REQUIRED" />
60             <tx:method name="update*" propagation="REQUIRED" />
61             <tx:method name="delete*" propagation="REQUIRED" />
62 
63             <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
64             <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
65             <tx:method name="select*" propagation="SUPPORTS" read-only="true" />
66             <tx:method name="load*" propagation="SUPPORTS" read-only="true" />
67 
68             其他采用默认事务方式
69             <tx:method name="*"  propagation="REQUIRED" />
70             
71         </tx:attributes>
72     </tx:advice>
73 
74     Spring aop事务管理  
75     <aop:config proxy-target-class="true">
76         配置切入点    指定这个aop:pointcut去引用上面规定的advice,也就是说规定下面的这个expression指定的路径下的service.impl下的所有的方法,都按照上面advice中的规定去执行,碰上什么操作,事务就是什么类型的,这就是事务管理器的好处了
77         解释一下,为什么这个要指定在service层:因为在同一个事务中,可能要对多张表进行多个不同的操作,才是一个完整的逻辑,例如淘宝上买东西,你转账之后你的钱减少了,对方的钱应该增加了,这两个操作在一起才是一个完整的操作,而如果这两个操作不在一个事务中,也就是如果将事务的操作指定在Dao层【MVC的设计模式:Dao层就是对数据库进行最简单的增删改查操作,而service层是进行逻辑处理的,一个完整的逻辑处理就要涉及到多次操作】事务操作失败,发生回滚,那你的帐减少了,对方的帐并没有增加,这样就不美丽的,因此,将事务的管理,指定在了service层
78         <aop:pointcut id="transactionPointcut"
79             expression="execution(* com.it.service..*Impl.*(..))" />expression中表达式所指意思: 所有的文件下的 com.it.service开头的包,以Impl结尾的类下的所有的方法,都执行上面advice的规定 
80         指定在txAdvice切入点应用txAdvice事务增强处理
81         <aop:advisor pointcut-ref="transactionPointcut"
82             advice-ref="transactionAdvice" />
83     </aop:config> -->
84     
85 </beans>
View Code

 

10.配置web.xml容器

 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 5     id="WebApp_ID" version="2.5">
 6 <!-- web容器是web项目的大脑 -->
 7 <!-- 在web.xml中,执行顺序是:1.先执行listener 2。再执行filter  3.最后执行servlet 这就是执行顺序 
 8     就像spring-hibernate.xml文件是在执行Listener的时候加载的,那注意这几个配置文件在web.xml中的加载顺序,因为资源文件是在配置文件【xml文件】中加载的,肯定是先加载的资源文件【properties文件】,才能在配置文件中调用资源文件中的变量的值使用
 9 
10  -->
11     <display-name>springmvc_demo</display-name>
12 <!-- web容器,首先需要引入spring,让spring管理各个框架,并将其注入为bean -->
13 <!-- 这个相当于定一个 变量在web.xml中,在下面的listener  org.springframework.web.context.ContextLoaderListener中,加载这个spring-hibernate.xml文件 -->
14     <context-param>
15         <param-name>contextConfigLocation</param-name>
16         <param-value>classpath:spring-hibernate.xml</param-value>
17     </context-param>
18 <!-- 配置控制层的filter信息 -->
19     <filter>
20         <filter-name>encodingFilter</filter-name>
21         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
22         <init-param>
23             <param-name>encoding</param-name>
24             <param-value>utf-8</param-value>
25         </init-param>
26         <init-param>
27             <param-name>forceEncoding</param-name>
28             <param-value>true</param-value>
29         </init-param>
30     </filter>
31     <filter-mapping>
32         <filter-name>encodingFilter</filter-name>
33         <url-pattern>/*</url-pattern>
34     </filter-mapping>
35 
36     <!-- openSessionInView配置 作用是延迟session关闭到view层 -->
37     <filter>
38         <filter-name>openSessionInViewFilter</filter-name>
39         <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
40         <init-param>
41             <param-name>singleSession</param-name>
42             <param-value>true</param-value>
43         </init-param>
44     </filter>
45 
46 <!-- 监听servletContext,启动contextConfigLocation中的spring配置信息 -->
47     <listener>
48         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
49     </listener>
50 
51 
52     <!-- 防止spring内存溢出监听器   可用可不用-->
53     <listener>
54         <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
55     </listener>
56 
57 
58 <!-- 类似与servlet 需要在web.xml中都需要配置一样,spring的思想是让这些servlet【controller也是servlet】继承了一个基础的servlet,那就只需在web.xml中配置一个servlet即可。 -->
59 <!-- 这个servlet和下面的servlet-mapping相配合使用,注明了所有的以.htmls结尾的请求都被截取到,去到servlet中去找相对应的方法 进行处理 -->
60     <servlet>
61         <description>spring mvc servlet</description>
62         <servlet-name>rest</servlet-name>
63         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
64         <init-param>
65             <param-name>contextConfigLocation</param-name>
66             <!-- 此处配置的是SpringMVC的配置文件 -->
67             <param-value>classpath:spring-mvc.xml</param-value>
68         </init-param>
69         <load-on-startup>1</load-on-startup>
70     </servlet>
71     <!-- 配置了springmvc拦截的url为以.hmls结尾的请求 -->
72     <servlet-mapping>
73         <servlet-name>rest</servlet-name>
74         <url-pattern>*.htmls</url-pattern>
75     </servlet-mapping>
76 
77     <filter-mapping>
78         <filter-name>openSessionInViewFilter</filter-name>
79         <url-pattern>/*</url-pattern>
80     </filter-mapping>
81 
82     <!-- 配置session超时时间,单位分钟 -->
83     <session-config>
84         <session-timeout>30</session-timeout>
85     </session-config>
86     <!-- 欢迎界面 默认的项目访问界面 -->
87     <welcome-file-list>
88         <welcome-file>/index.jsp</welcome-file>
89     </welcome-file-list>
90 </web-app>
View Code

 

11.创建Controller层

 

 1 package com.it.controller;
 2 
 3 import java.sql.Timestamp;
 4 import java.util.List;
 5 import java.util.UUID;
 6 
 7 import javax.annotation.Resource;
 8 
 9 import org.apache.log4j.Logger;
10 import org.springframework.stereotype.Controller;
11 import org.springframework.ui.ModelMap;
12 import org.springframework.web.bind.annotation.PathVariable;
13 import org.springframework.web.bind.annotation.RequestMapping;
14 import org.springframework.web.bind.annotation.ResponseBody;
15 
16 import com.it.entity.Myuser;
17 import com.it.service.MyUserService;
18 
19 
20 
21 
22 @Controller
23 @RequestMapping("/myuser")
24 public class MyUserController {
25     
26     private static final Logger LOGGER = Logger.getLogger(MyUserController.class);
27     
28     
29     @Resource( name = "myUserService")
30     private MyUserService  myUserService;
31     
32     
33     @RequestMapping("/saveOne")
34     public String saveOne(){
35         Myuser myuser = new Myuser();
36         //myuser.setMyUserId(UUID.randomUUID().toString());
37         myuser.setMyUserName("andy");
38         myuser.setMyUserPhone("13823237878");
39         myuser.setMyUserTime(Timestamp.valueOf("1995-09-15 12:12:12"));
40         myUserService.save(myuser);
41         return "/user/showInfo";
42     }
43     
44     @RequestMapping("/showInfo/{userId}")
45     public String showUserInfo(ModelMap model, @PathVariable String userId){
46         LOGGER.info("查询用户:"+userId);
47         Myuser myuser = myUserService.load(userId);
48         model.addAttribute("userInfo", myuser);
49         return "/user/showInfo";
50     }
51     
52     
53     @RequestMapping("/showInfos")
54     public @ResponseBody List<Myuser> showAllUser(){
55         LOGGER.info("查询所有用户");
56         List<Myuser> list = myUserService.findAll();
57         return list;
58     }
59 }
View Code

 

 

12.创建view视图层

在src/main/webapp/WEB-INF/views下 创建user/showInfo.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
 2 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 3 <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
 4 
 5 <%
 6     String path = request.getContextPath();
 7     String basePath = request.getScheme() + "://"
 8             + request.getServerName() + ":" + request.getServerPort()
 9             + path + "/";
10 %>
11 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
12 <html>
13 <head>
14 <base href="<%=basePath%>" />
15 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
16 <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
17 <title>用户信息展示</title>
18 </head>
19 <body>
20     用户信息 昵称: ${userInfo.myUserName} 用户id:${userInfo.myUserId} 用户电话:${userInfo.myUserPhone } 注册时间:
21     <fmt:formatDate value="${userInfo.myUserTime }" pattern="yyyy-MM-dd HH:mm:ss" />
22     角色:[
23     <c:forEach items="${ userInfo.roles}" var="role">
24                         ${role.roleName }   权限[
25                            <c:forEach items="${ role.authorities}" var="authority">
26                              ${authority.authorityName } 
27                            </c:forEach> ]
28                       </c:forEach>
29     ]
30 
31     <br /> ajax显示全部用户信息:
32     <div id="show_all_user"></div>
33 </body>
34 <script type="text/javascript">
35     $.ajax({
36         type : "get",
37         url : "myuser/showInfos.htmls",
38         dataType : "json",
39         success : function(data) {
40             $(data).each(
41                     function(i, user) {
42                         var p = "<p>昵称:" + user.myUserName + "    电话:"
43                                 + user.myUserPhone + "    注册时间:"
44                                 + user.myUserTime + "    id:" + user.myUserId +
45                         "</p>";
46                         $("#show_all_user").append(p);
47                     });
48         },
49         async : true
50     });
51 </script>
52 </html>
View Code

 13. 一切准备就绪,把项目部署到tomcat中,启动即可

 

可能你会说,那要这个view页面做什么??因为参考别人的嘛 并且,这个页面比较值得钻研

网友评论

登录后评论
0/500
评论
angel挤一挤
+ 关注