引言:Spring真可谓“春天”啊。Spring中,常用的是Spring FrameWork,其他模块也越来越多,支持的也越来越好,如,Spring Boot、Spring Data、Spring Batch、Spring Security、Spring Social、Spring Mobile、Spring Web Flow、Spring Web Services、Spring Ldap和Spring Session等。看到这些,想必能联想到很多吧,各式各样的功能,各式各样的服务,已将尽收囊中。本文介绍的就是Spring Data中的JPA的集成使用。
下面就从一个Java Web项目创建开始吧。
首先说明一下,此例中,工具使用Eclipse(Version: Indigo Service Release 2),应用服务使用Tmocat-6.0.35,数据库使用MySql。
一、创建项目
1. 新建一个Java Web项目
(1)”New”->”Dynamic Web Project”,输入项目名:stark-spring-jpa-demo,点击”Next”;
(2)这一步可以修改编译之后class的生成目录,默认是”build\classes”,如果需要兼容MyEclipse等工具(即项目可以直接导入跑通),最好修改成”WebRoot\WEB-INF\classes”,博主这里就使用兼容的吧,修改路径之后,点击”Next”;
(3)这一步默认的目录是WebContent,如果编译目录使用默认的,这里就不用改了。因为博主上面使用了”WebRoot\WEB-INF\classes”,所以这一步中就将目录改成”WebRoot”了,直接点击”Finish”;
注意点:项目创建完成之后,最好查看一下项目的编码,如果工具没有设置,请改成UTF-8。
(4)项目创建完成
目录如下;
(5)导入所需的JAR包
注意:查看一下JAR包是否被引用了,如果没有,可以编译或刷新一下项目。
二、web.xml的配置
直接看配置文件吧,如下:
<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app version=”2.5″
xmlns=”http://java.sun.com/xml/ns/javaee”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd”>
<!– 初始化bean容器 –>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!– spring mvc 配置 –>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!– 转换编码为UTF-8 –>
<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>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
三、初始化bean配置(集成Jpa等配置),创建源码目录,配置log4j
1. 在src下创建源码包同时创建”applicationContext.xml”和”application.properties”两个配置文件,再加入”log4j.properties”
如图:
说明:
applicationContext.xml文件主要配置,Spring的注解模式、Jpa的数据接口仓库、数据源、事务等。
application.properties文件,主要配置本项目的常量。
log4j.properties文件,配置log4j,用于日志。
(1)applicationContext.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”
xmlns:tx=”http://www.springframework.org/schema/tx” xmlns:mvc=”http://www.springframework.org/schema/mvc”
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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd”>
<!– 开启注解模式 –>
<mvc:annotation-driven />
<!– 注解扫描配置 –>
<context:component-scan base-package=”com.stark.demo” />
<!– jpa dao接口包配置 –>
<jpa:repositories base-package=”com.stark.demo.dao”/>
<!– 数据源配置文件 –>
<context:property-placeholder location=”classpath:/application.properties” />
<!– 数据源配置 –>
<bean id=”dataSource” class=”org.apache.commons.dbcp.BasicDataSource” destroy-method=”close”>
<property name=”driverClassName” value=”${app.jdbc.driverClass}”></property>
<property name=”url” value=”${app.jdbc.url}”></property>
<property name=”username” value=”${app.jdbc.username}”></property>
<property name=”password” value=”${app.jdbc.password}”></property>
<property name=”initialSize” value=”${app.jdbc.initialSize}”></property>
<property name=”maxActive” value=”${app.jdbc.maxActive}”></property>
<property name=”maxIdle” value=”${app.jdbc.maxIdle}”></property>
<property name=”maxWait” value=”${app.jdbc.maxWait}”></property>
<property name=”minIdle” value=”${app.jdbc.minIdle}”></property>
</bean>
<!– 持久化实现类 –>
<bean id=”persistenceProvider” class=”org.hibernate.ejb.HibernatePersistence” />
<!–JPA特定属性配置 –>
<bean id=”jpaVendorAdapter” class=”org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter”>
<property name=”generateDdl” value=”true” />
<property name=”showSql” value=”true” />
<property name=”database” value=”${app.jdbc.dbType}” />
</bean>
<!– 高级特性配置 –>
<bean id=”jpaDialect” class=”org.springframework.orm.jpa.vendor.HibernateJpaDialect”></bean>
<!– entityManagerFactory –>
<bean id=”entityManagerFactory” class=”org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean”>
<property name=”dataSource” ref=”dataSource”/>
<property name=”packagesToScan” value=”com.stark.demo.entitys” /><!– jpa实体包 –>
<property name=”persistenceProvider” ref=”persistenceProvider” />
<property name=”jpaVendorAdapter” ref=”jpaVendorAdapter” />
<property name=”jpaDialect” ref=”jpaDialect” />
</bean>
<!– 事务管理器 –>
<bean id=”transactionManager” class=”org.springframework.orm.jpa.JpaTransactionManager”>
<property name=”entityManagerFactory” ref=”entityManagerFactory” />
</bean>
<tx:annotation-driven transaction-manager=”transactionManager” />
</beans>
(2)application.properties
#数据源参数配置app.jdbc.dbType=MYSQLapp.jdbc.driverClass=com.mysql.jdbc.Driver###本地数据库###app.jdbc.url=jdbc:mysql://localhost:3306/spring-jpa-demo?useUnicode=true&characterEncoding=UTF-8app.jdbc.username=<用户名>app.jdbc.password=<密码>###数据库连接池相关配置###app.jdbc.initialSize=5app.jdbc.maxActive=10app.jdbc.maxIdle=8app.jdbc.maxWait=28000app.jdbc.minIdle=3
注:请在本地Mysql中创建名为”spring-jpa-demo”的数据库。
(3)log4j.properties
如下:
# OFF、FATAL、ERROR、WARN、INFO、DEBUG、ALLlog4j.rootLogger=DEBUG,STDOUT,ERRORlog4j.appender.STDOUT=org.apache.log4j.ConsoleAppenderlog4j.appender.STDOUT.layout=org.apache.log4j.PatternLayoutlog4j.appender.STDOUT.layout.ConversionPattern=[PROJECT][%d{yyyy-MM-dd HH\:mm\:ss}][%p]-%m%n
说明:这里面只做相应的输出提醒,如需要生成文件,请自行配置。
四、创建和配置spring-servlet.xml
只要知道Java Web项目的运行机制的都了解,在web.xml中配置的servlet,如果没有配置其加载文件地址的话,会默认加载与web.xml同级目录中的<servlet名称>-servlet.xml文件,因为上面web.xml中配置的servlet的名称是spring,即会加载spring-servlet.xml,这个文件主要配置spring的视图等。
具体操作:
(1)在web.xml下创建spring-servlet.xml,即WEB-INF目录下创建
(2)配置该文件
如下:
<?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:p=”http://www.springframework.org/schema/p”
xsi:schemaLocation=”
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd”>
<!– 配置jsp视图 –>
<bean id=”jspViewResolver” class=”org.springframework.web.servlet.view.InternalResourceViewResolver”>
<property name=”suffix” value=”.jsp” />
</bean>
<!– 支持不同的请求方式及编码 –>
<bean class=”org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter”
p:ignoreDefaultModelOnRedirect=”true”>
<property name=”messageConverters”>
<list>
<bean class=”org.springframework.http.converter.json.MappingJacksonHttpMessageConverter” />
<bean class=”org.springframework.http.converter.ByteArrayHttpMessageConverter” />
<bean class=”org.springframework.http.converter.BufferedImageHttpMessageConverter” />
<bean class=”org.springframework.http.converter.StringHttpMessageConverter”>
<property name=”supportedMediaTypes”>
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
</beans>
至此,框架的配置文件已经完成了。
咱们框架配置已经好了,想必您已迫不及待想编写自己的程序了吧。下面博主就简单的来测试一下。
五、编码测试
1. 创建User实体
如下:
package com.stark.demo.entitys;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;/*** 用户实体类* @author stark*/@Entity@Table(name=”USER”)public class User implements Serializable {private static final long serialVersionUID = -6395834411937686352L;@Id@Column(name = “ID”, length = 32)@GeneratedValue(generator = “system-uuid”)@GenericGenerator(name = “system-uuid”, strategy = “uuid”)private String id;//唯一id,使用uuid生成策略@Column(name = “NAME”, length = 50)private String name;//用户名@Column(name = “PWD”, length = 50)private String pwd;//用户密码public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}}
2. 创建User基于Jpa的数据接口UserDao
如下:
package com.stark.demo.dao;import org.springframework.data.repository.CrudRepository;import com.stark.demo.entitys.User;public interface UserDao extends CrudRepository<User, String> {}
3. 创建业务层UserService接口和其实现类UserServiceImpl
如下:
(1)UserService
package com.stark.demo.service;import java.util.List;import com.stark.demo.entitys.User;public interface UserService {/*** 保存User对象* @param vo* @return* @throws Exception*/public User saveVo(User vo) throws Exception;/*** 根据id获取User对象* @param id* @return* @throws Exception*/public User loadVo(String id) throws Exception;/*** 查询所有的User* @return* @throws Exception*/public List<User> findAllList() throws Exception;}
(2)UserServiceImpl
package com.stark.demo.service;import java.util.List;import org.apache.openjpa.persistence.ReadOnly;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import com.stark.demo.dao.UserDao;import com.stark.demo.entitys.User;@Service(“userService”)@Transactionalpublic class UserServiceImpl implements UserService {@Autowiredprivate UserDao userDao;@Transactional(rollbackFor = { Exception.class })public User saveVo(User vo) throws Exception {User user = null;try {user = this.userDao.save(vo);} catch (Exception e) {System.out.println(“出错信息:” + e.getMessage());}return user;}@ReadOnlypublic User loadVo(String id) throws Exception {User user = null;try {user = this.userDao.findOne(id);} catch (Exception e) {System.out.println(“出错信息:” + e.getMessage());}return user;}@ReadOnlypublic List<User> findAllList() throws Exception {List<User> userList = null;try {userList = (List<User>) this.userDao.findAll();} catch (Exception e) {System.out.println(“出错信息:” + e.getMessage());}return userList;}}
4. 创建UserController
如下:
package com.stark.demo.controller;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import com.stark.demo.entitys.User;import com.stark.demo.service.UserService;@Controller@RequestMapping(“user”)public class UserController {@Autowiredprivate UserService userService;/*** 新增用户,并返回新增之后的用户信息页面* @param request* @param response* @return* @throws Exception*/@RequestMapping(“/addUser.do”)public String addUser(HttpServletRequest request, HttpServletResponse response,Model model) throws Exception{String name = request.getParameter(“name”);String pwd =request.getParameter(“pwd”);User user = new User();user.setName(name);user.setPwd(pwd);user = this.userService.saveVo(user);model.addAttribute(“user”, user);return “/WEB-INF/jsp/result”;}/*** 根据id获取用户信息* @param request* @return* @throws Exception*/@ResponseBody@RequestMapping(“/getUser.do”)public Object loadUser(HttpServletRequest request) throws Exception{String id = request.getParameter(“id”);User user = this.userService.loadVo(id);return user;}}
注:因为要测试页面的跳转,所以在”WEB-INF”目录下创建了jsp目录,在其下新建了”result.jsp”,如下:
<%@ page language=”java” contentType=”text/html; charset=utf-8″ pageEncoding=”UTF-8″%><!DOCTYPE html><html><head><meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″><title>新增用户信息</title></head><body><div>ID:${user.id}</div><div>用户名:${user.name}</div><div>密码:${user.pwd}</div></body></html>
5. 部署至Tomcat,启动项目
启动之前先看下现在的目录:
(1)新增
打开浏览器,输入:http://localhost:8082/stark-spring-jpa-demo/user/addUser.do?name=test&pwd=123456
其中端口根据个人设置修改即可。
效果如下:
(2)获取用户信息
在浏览器中输入:http://localhost:8082/stark-spring-jpa-demo/user/getUser.do?id=8a8a8a8150d0f55d0150d0f6f86b0001
效果如下:
至此编码的测试也尾声了。
如有问题,欢迎指出;如需转载,请标明出处,谢谢!