spring mvc 与JPA/Hibernate的整合示例

简介:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
一、首先通过maven加入spring、jpa和hibernate相关的jar包。如pom.xml:
Java代码  收藏代码
     <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> cn.ibeans</groupId>
       <artifactId>ibeans</artifactId>
       <packaging>war</packaging>
       <version> 0.0 . 1 -SNAPSHOT</version>
       <name>myweb Maven Webapp</name>
       <url>http: //maven.apache.org</url>
                    
       <!-- 定义相关属性 -->
       <properties>
         <jdk-version> 1.6 </jdk-version>
         <junit-version> 4.11 </junit-version>
         <spring-version> 3.2 . 2 .RELEASE</spring-version>
       </properties>
                    
       <!-- 定义依赖包 -->
       <dependencies>
         <!-- spring begin-->
         <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-web</artifactId>
             <version>${spring-version}</version>
         </dependency>
         <dependency>
             <groupId>org.springframework</groupId>
             <artifactId>spring-webmvc</artifactId>
             <version>${spring-version}</version>
         </dependency>
         <dependency>
             <groupId>org.springframework</groupId>
             <artifactId>spring-context</artifactId>
             <version>${spring-version}</version>
         </dependency>
         <dependency>
             <groupId>org.springframework.data</groupId>
             <artifactId>spring-data-jpa</artifactId>
             <version> 1.3 . 2 .RELEASE</version>
         </dependency>
         <!-- spring end -->
                      
                      
         <!-- servlet begin -->
         <dependency>
             <groupId>javax.servlet</groupId>
             <artifactId>servlet-api</artifactId>
             <version> 3.0 -alpha- 1 </version>
             <scope>provided</scope>
         </dependency>
         <!-- servlet end -->
                      
                      
         <!-- junit begin -->
         <dependency>
             <groupId>junit</groupId>
             <artifactId>junit</artifactId>
             <version>${junit-version}</version>
             <scope>test</scope>
         </dependency>
         <!-- junit end -->
                      
                      
         <!-- hibernate begin -->
         <dependency>
             <groupId>org.hibernate</groupId>
             <artifactId>hibernate-core</artifactId>
             <version> 4.2 . 1 .Final</version>
         </dependency>
             <dependency>
             <groupId>org.hibernate</groupId>
             <artifactId>hibernate-entitymanager</artifactId>
             <version> 4.2 . 1 .Final</version>
         </dependency>
         <dependency>
             <groupId>org.hibernate.common</groupId>
             <artifactId>hibernate-commons-annotations</artifactId>
             <version> 4.0 . 1 .Final</version>
         </dependency>
         <dependency>
             <groupId>org.hibernate</groupId>
             <artifactId>hibernate-validator</artifactId>
             <version> 5.0 . 0 .Final</version>
         </dependency>
         <!-- hibernate end -->
                      
                      
         <!--logger begin -->
         <dependency>
             <groupId>org.slf4j</groupId>
             <artifactId>slf4j-api</artifactId>
             <version> 1.7 . 5 </version>
         </dependency>
         <dependency>
             <groupId>org.slf4j</groupId>
             <artifactId>jcl-over-slf4j</artifactId>
             <version> 1.7 . 5 </version>
         </dependency>
         <dependency>
             <groupId>org.slf4j</groupId>
             <artifactId>slf4j-log4j12</artifactId>
             <version> 1.7 . 5 </version>
         </dependency>
         <!-- logger end -->
                      
                      
         <!-- database begin -->
         <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
             <version> 5.1 . 25 </version>
         </dependency>
         <!-- database end -->
                      
                      
         <!-- apache commons begin -->
         <dependency>
             <groupId>commons-dbcp</groupId>
             <artifactId>commons-dbcp</artifactId>
             <version> 20030825.184428 </version>
         </dependency>
         <dependency>
             <groupId>commons-pool</groupId>
             <artifactId>commons-pool</artifactId>
             <version> 20030825.183949 </version>
         </dependency>
         <dependency>
             <groupId>commons-collections</groupId>
             <artifactId>commons-collections</artifactId>
             <version> 2.1 </version>
         </dependency>
         <!-- apache commons end -->
       </dependencies>
                    
       <!-- 配置构建 -->
       <build>
         <finalName>ibeans</finalName>
       </build>
     </project>
2 、配置applicationContext.xml中的实体管理工厂和事务机制:
Java代码  收藏代码
     <?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" 
         xmlns:jdbc= "http://www.springframework.org/schema/jdbc"  
         xmlns:jee= "http://www.springframework.org/schema/jee" 
         xmlns:tx= "http://www.springframework.org/schema/tx"
         xmlns:jpa= "http://www.springframework.org/schema/data/jpa"
         xsi:schemaLocation="
             http: //www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
             http: //www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
             http: //www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
             http: //www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
             http: //www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
             http: //www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
         default -lazy-init= "true" >
                  
         <description>Spring公共配置 </description>
                  
         <!-- 使用annotation 自动注册bean, 并保证 @Required @Autowired 的属性被注入 -->
         <context:component-scan base- package = "cn.ibeans" >
             <context:exclude-filter type= "annotation"  expression= "org.springframework.stereotype.Controller" />
         </context:component-scan>
                  
         <!-- JPA实体管理工厂的配置 -->
         <bean id= "entityManagerFactory"  class = "org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
             <property name= "dataSource"  ref= "dataSource" />
             <property name= "jpaVendorAdapter"  ref= "hibernateJpaVendorAdapter" />
             <property name= "packagesToScan"  value= "cn.ibeans" /><!--待扫描的实体类包,不再需要persistence.xml了-->
             <property name= "jpaProperties" >
                 <props>
                     <prop key= "hibernate.ejb.naming_strategy" >org.hibernate.cfg.ImprovedNamingStrategy</prop>
                     <prop key= "hibernate.show_sql" > true </prop>
                     <prop key= "hibernate.hbm2ddl.auto" >update</prop>
                 </props>
             </property>
         </bean>
                      
         <!--指定实现JPA的适配器-->
         <bean id= "hibernateJpaVendorAdapter"  class = "org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" >
             <property name= "databasePlatform"  value= "org.hibernate.dialect.MySQLDialect"  />
         </bean>
                      
         <!-- Jpa 事务配置 -->
         <bean id= "transactionManager"  class = "org.springframework.orm.jpa.JpaTransactionManager" >
             <property name= "entityManagerFactory"  ref= "entityManagerFactory" />
         </bean>
                      
         <!-- Spring Data Jpa配置 -->
         <!--
         <jpa:repositories base- package = "cn.ibeans"   transaction-manager-ref= "transactionManager"  entity-manager-factory-ref= "entityManagerFactory" />
         -->
         <!-- 使用annotation定义事务 -->
         <tx:annotation-driven transaction-manager= "transactionManager"  proxy-target- class = "true"  />
                  
         <!-- JSR303 Validator定义 -->
         <bean id= "validator"  class = "org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"  />
                      
         <!-- production环境 -->
         <beans profile= "production" >
             <context:property-placeholder ignore-unresolvable= "true"  location= "classpath*:/db.properties"  />  
                          
             <!-- 数据源配置, 使用DBCP数据库连接池 -->
             <bean id= "dataSource"  class = "org.apache.commons.dbcp.BasicDataSource"  destroy-method= "close" >
                 <!-- Connection Info -->
                 <property name= "driverClassName"  value= "${jdbc.driver}"  />
                 <property name= "url"  value= "${jdbc.url}"  />
                 <property name= "username"  value= "${jdbc.username}"  />
                 <property name= "password"  value= "${jdbc.password}"  />
                          
                 <!-- Connection Pooling Info -->
                 <property name= "maxActive"  value= "${dbcp.maxActive}"  />
                 <property name= "maxIdle"  value= "${dbcp.maxIdle}"  />
                 <property name= "defaultAutoCommit"  value= "false"  />
                 <!-- 连接Idle一个小时后超时 -->
                 <property name= "timeBetweenEvictionRunsMillis"  value= "3600000"  />
                 <property name= "minEvictableIdleTimeMillis"  value= "3600000"  />
             </bean>
                          
             <!-- 数据源配置,使用应用服务器的数据库连接池 -->
             <!--<jee:jndi-lookup id= "dataSource"  jndi-name= "java:comp/env/jdbc/ExampleDB"  />-->
         </beans>
                      
         <!-- local development环境 -->
         <beans profile= "development" >
             <context:property-placeholder ignore-resource-not-found= "true"
                 location="classpath*:/db.properties,
                           classpath*:/db_dev.properties" />  
                  
             <!-- DBCP连接池 -->
             <bean id= "dataSource"  class = "org.apache.commons.dbcp.BasicDataSource"  destroy-method= "close" >
                 <property name= "driverClassName"  value= "${jdbc.driver}"  />
                 <property name= "url"  value= "${jdbc.url}"  />
                 <property name= "username"  value= "${jdbc.username}"  />
                 <property name= "password"  value= "${jdbc.password}"  />
                 <property name= "defaultAutoCommit"  value= "false"  />
             </bean>
         </beans>
                      
         <!-- unit test环境 -->
         <beans profile= "test" >
             <context:property-placeholder ignore-resource-not-found= "true"
                 location= "classpath*:/db_test.properties"  /> 
                          
             <!-- Simple连接池 -->
             <bean id= "dataSource"  class = "org.springframework.jdbc.datasource.SimpleDriverDataSource" >
                 <property name= "driverClass"  value= "${jdbc.driver}"  />
                 <property name= "url"  value= "${jdbc.url}"  />
                 <property name= "username"  value= "${jdbc.username}"  />
                 <property name= "password"  value= "${jdbc.password}"  />
             </bean>
                  
             <!-- 初始化数据表结构 与默认数据-->
             <jdbc:initialize-database data-source= "dataSource"  ignore-failures= "ALL" >
                 <jdbc:script location= "classpath:sql/h2/schema.sql"  />
                 <jdbc:script location= "classpath:data/import-data.sql"  encoding= "UTF-8" />
             </jdbc:initialize-database>
         </beans>
     </beans>
定义实体类:User.java
Java代码  收藏代码
     package  cn.ibeans.web.model;
                  
     import  java.io.Serializable;
                  
     import  javax.persistence.Column;
     import  javax.persistence.Entity;
     import  javax.persistence.GeneratedValue;
     import  javax.persistence.Id;
     import  javax.persistence.Table;
                  
     import  org.hibernate.annotations.GenericGenerator;
                  
     @Entity
     @Table (name= "i_user" )
     public  class  User  implements  Serializable{
         private  String id;
         private  String username;
         private  String password;
                      
         @Id
         @GeneratedValue (generator= "system-uuid" )
         @GenericGenerator (name= "system-uuid" ,strategy= "uuid" )
         public  String getId() {
             return  id;
         }
         public  void  setId(String id) {
             this .id = id;
         }
                      
         @Column (name= "username" )
         public  String getUsername() {
             return  username;
         }
         public  void  setUsername(String username) {
             this .username = username;
         }
                      
         @Column (name= "password" )
         public  String getPassword() {
             return  password;
         }
         public  void  setPassword(String password) {
             this .password = password;
         }
                      
     }
3 、定义dao接口,只需定义接口方法即可,不用加任何注解
Java代码  收藏代码
     package  cn.ibeans.dao;
                  
     import  cn.ibeans.web.model.User;
                  
     public  interface  UserDao {
                  
         User findByName(String name);
                  
         User findByLoginName(String loginName);
                      
         void  saveOrUpdate(User user);
     }
4 、定义dao实现类。用 @Repository 注解类,并将EntityManager作为成员变量注入,注入方法是加 @PersistenceContext
Java代码  收藏代码
     package  cn.ibeans.dao.impl;
                  
     import  javax.persistence.EntityManager;
     import  javax.persistence.PersistenceContext;
                  
     import  org.springframework.stereotype.Repository;
                  
     import  cn.ibeans.dao.UserDao;
     import  cn.ibeans.web.model.User;
                  
     @Repository
     public  class  UserDaoImpl  implements  UserDao {
                      
         @PersistenceContext
         private  EntityManager em;
                  
         @Override
         public  User findByName(String name) {
             return  null ;
         }
                  
         @Override
         public  User findByLoginName(String loginName) {
             return  null ;
         }
                  
         @Override
         public  void  saveOrUpdate(User user) {
             em.persist(user);
         }
                  
     }
5 、定义service类。可直接写实现类
@Component @Service 注释类,将dao接口作为成员变量注入,注入方法是加 @Autowired
如果是写方法,需在方法上加 @Transactional (readOnly= false )注解
Java代码  收藏代码
     package  cn.ibeans.service;
                  
     import  javax.annotation.Resource;
                  
     import  org.apache.log4j.Logger;
     import  org.springframework.beans.factory.annotation.Autowired;
     import  org.springframework.stereotype.Component;
     import  org.springframework.transaction.annotation.Transactional;
                  
     import  cn.ibeans.dao.UserDao;
     import  cn.ibeans.web.model.User;
                  
     @Component
     public  class  UserService {
         private  static  Logger logger = Logger.getLogger(UserService. class );
         @Autowired
         private  UserDao userDao;
                      
         @Transactional (readOnly= false )
         public  void  saveUser(User user){
             userDao.saveOrUpdate(user);
             logger.debug(user.getUsername()+ ",保存成功!" );
         }
     }
6 、定义action
@Controller 注释action类,如果需为该action中所有方法指定一个共用的上层路径名,则需用 @RequestMapping (value= "/user" )注释该类。表示该类下的所有访求均要通过/user/**来访问
将service类作为成员变量注入action。注入方法是加 @Autowired
@RequestMapping (value= "/save" )注释action的方法。
Java代码  收藏代码
     package  cn.ibeans.web.controller;
                  
     import  javax.servlet.ServletContext;
     import  javax.servlet.http.HttpServlet;
                  
     import  org.apache.log4j.Logger;
     import  org.springframework.beans.factory.annotation.Autowired;
     import  org.springframework.stereotype.Controller;
     import  org.springframework.ui.Model;
     import  org.springframework.web.bind.annotation.ModelAttribute;
     import  org.springframework.web.bind.annotation.RequestMapping;
     import  org.springframework.web.context.ContextLoader;
     import  org.springframework.web.context.WebApplicationContext;
                  
     import  cn.ibeans.service.UserService;
     import  cn.ibeans.web.model.User;
                  
     @Controller
     @RequestMapping (value= "/user" )
     public  class  LoginController  extends  HttpServlet{
         private  static  Logger log = Logger.getLogger(LoginController. class );
                      
         @Autowired
         private  UserService userService;
                      
                  
         //@RequestMapping(value="/login")   //如果类级别上已有映射地址(/user),此处的完整请求地址是/user/login
         public  String doLogin(Model model,Object loginForm){
             //model.addAttribute("username",username);  //model被用来封装数据,向前台传递
             WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
             ServletContext sc = context.getServletContext();
                          
             return  "/welcome" ;
         }
                      
         @RequestMapping (value= "/login" )
         public  String login( @ModelAttribute  User user,Model model){
             log.info(user.getUsername());
             model.addAttribute(user);
             return  "/welcome" ;
         }
                      
         @RequestMapping (value= "/save" )
         public  String save( @ModelAttribute  User user,Model model){
             log.info(user.getUsername());
             userService.saveUser(user);
             model.addAttribute(user);
             return  "/welcome" ;
         }
     }
7 、发起请示的页面
请示的url应该是上下文根路径+action类路径+方法路径
Java代码  收藏代码
     <%@ page language= "java"  contentType= "text/html; charset=utf-8"  pageEncoding= "utf-8" %>
      <!DOCTYPE html PUBLIC  "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd" >
      <html>
      <head>
      <meta http-equiv= "Content-Type"  content= "text/html; charset=utf-8" >
      <title>Insert title here</title>
      </head>
      <body>
          <div>
              <form action= "/ibeans/user/save"  methed= "post" >
                  <input type= "text"  name= "username" >
                  <input type= "text"  name= "password" >
                  <input type= "submit"  value= "SUBMIT" >
              </form>
          </div>
      </body>
      </html>
8 、转发目的页面
可以通过引用action方法里定义的mode属性来获取相关的数据。
welcome.jsp:
Java代码  收藏代码
     <%@ page language= "java"  contentType= "text/html; charset=utf-8"
         pageEncoding= "utf-8" %>
     <!DOCTYPE html PUBLIC  "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd" >
     <html>
     <head>
     <meta http-equiv= "Content-Type"  content= "text/html; charset=utf-8" >
     <title>Insert title here</title>
     </head>
     <body>
        ${user.username },你好! 
     </body>
     </html>


















本文转自yunlielai51CTO博客,原文链接:http://blog.51cto.com/4925054/1282960,如需转载请自行联系原作者

相关文章
|
6天前
|
前端开发 Java 测试技术
Java一分钟之Spring MVC:构建Web应用
【5月更文挑战第15天】Spring MVC是Spring框架的Web应用模块,基于MVC模式实现业务、数据和UI解耦。常见问题包括:配置DispatcherServlet、Controller映射错误、视图解析未设置、Model数据传递遗漏、异常处理未配置、依赖注入缺失和忽视单元测试。解决这些问题可提升代码质量和应用性能。注意配置`web.xml`、`@RequestMapping`、`ViewResolver`、`Model`、`@ExceptionHandler`、`@Autowired`,并编写测试用例。
293 3
|
4天前
|
前端开发 Java 关系型数据库
使用IDEA搭建一个Spring + AOP (权限管理 ) + Spring MVC
使用IDEA搭建一个Spring + AOP (权限管理 ) + Spring MVC
|
6天前
|
JSON 前端开发 Java
【JavaEE】让“单车变摩托”的神级框架—Spring MVC的深入讲解(下)
【JavaEE】让“单车变摩托”的神级框架—Spring MVC的深入讲解
7 0
|
6天前
|
JSON 前端开发 Java
【JavaEE】让“单车变摩托”的神级框架—Spring MVC的深入讲解(上)
【JavaEE】让“单车变摩托”的神级框架—Spring MVC的深入讲解
7 0
|
6天前
|
设计模式 前端开发 Java
初识Spring MVC
初识Spring MVC
14 0
|
6天前
|
前端开发 Java 应用服务中间件
Spring MVC框架概述
Spring MVC 是一个基于Java的轻量级Web框架,采用MVC设计模型实现请求驱动的松耦合应用开发。框架包括DispatcherServlet、HandlerMapping、Handler、HandlerAdapter、ViewResolver核心组件。DispatcherServlet协调这些组件处理HTTP请求和响应,Controller处理业务逻辑,Model封装数据,View负责渲染。通过注解@Controller、@RequestMapping等简化开发,支持RESTful请求。Spring MVC具有清晰的角色分配、Spring框架集成、多种视图技术支持以及异常处理等优点。
20 1
|
6天前
|
监控 前端开发 Java
SpringBoot与SpringMVC有哪些区别?
SpringBoot和SpringMVC是Java开发中常用的两个框架,它们都是由Spring框架所提供的,但在功能和使用方式上有着一些区别。
24 2
|
6天前
|
SQL Java 数据库连接
Springboot框架整合Spring Data JPA操作数据
Spring Data JPA是Spring基于ORM和JPA规范封装的框架,简化了数据库操作,提供增删改查等接口,并可通过方法名自动生成查询。集成到Spring Boot需添加相关依赖并配置数据库连接和JPA设置。基础用法包括定义实体类和Repository接口,通过Repository接口可直接进行数据操作。此外,JPA支持关键字查询,如通过`findByAuthor`自动转换为SQL的`WHERE author=?`查询。
|
6天前
|
数据采集 前端开发 Java
数据塑造:Spring MVC中@ModelAttribute的高级数据预处理技巧
数据塑造:Spring MVC中@ModelAttribute的高级数据预处理技巧
24 3
|
6天前
|
存储 前端开发 Java
会话锦囊:揭示Spring MVC如何巧妙使用@SessionAttributes
会话锦囊:揭示Spring MVC如何巧妙使用@SessionAttributes
14 1