从最基本的Java工程搭建SpringMVC+SpringDataJPA+Hibernate
本文会介绍从一个最基本的java工程,到Web工程,到集成Spring、SpringMVC、SpringDataJPA+Hibernate。
平时我们可能是通过一个模板搭建一个工程,或者是直接导入一个项目,而本文选择从最基本的java工程开始,目的是为了展示更多原理。
当然,我们还是从一个最基本的Maven工程开始,其实普通的非Maven工程,搭建过程几乎是一模一样的,只是Jar包需要我们手动的添加到工程中,而Maven工程就只是修改配置文件即可。
下面就正式开始。
1、基于Maven(如果不使用Maven也可以用传统的工程)创建最基本的Java工程
新建工程,选择Maven Project,Next:
勾选为简单的工程(Create a simple project),Next:
Group id为你的域名反序,通常跟工程源码的包名对应,Artifact id为这个Group id中工程的唯一名,根据你的爱好,怎么填都行,然后Finish:
这是得到的工程目录结构是这样的:
pom.xml就是Maven的核心文件。
2、将工程设置为动态网页模式
接下来就将工程转换为Web工程,右键打开工程属性,如图,点击左边菜单中的Project Facets,然后点击Convert to faceted from...:
在右边,我们勾选Dynamic Web Module(动态网页),然后点OK:
这时会多出一个WebContent目录:
在WEB-INF目录下,添加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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>SpringDataJPA</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
然后添加一个欢迎页index.html:
<html>
<head>
</head>
<body>
<h1>Hello Word!</h1>
</body>
</html>
这时目录结构如下:
这时,就可以右键工程,Run On Server了,可以看下效果:
3、集成Spring+SpringMVC
新建包,并添加一些接口和类(具体代码后面会列出来),包结构如图:
需要添加jar包,直接修改pom文件即可,如果为普通工程,按pom.xml中的jar包,添加到工程中即可。
首先添加使用的spring版本,方便统一管理,然后再添加所有需要的jar包,下面把此处需要的所有jar包添加进来,完成后的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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.anxpp</groupId>
<artifactId>SpringDataJPA</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<!-- spring版本号 -->
<spring.version>4.2.5.RELEASE</spring.version>
</properties>
<dependencies>
<!-- spring核心包 -->
<groupId>org.springframework</groupId>
<artifactId>spring-core</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-orm</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-jdbc</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-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.10.1.RELEASE</version>
</dependency>
</dependencies>
</project>
在WEB-INF目录下添加Spring配置文件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:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
<!-- 开启IOC注解扫描 -->
<context:component-scan base-package="com.anxpp.demo" />
<!-- 开启MVC注解扫描 -->
<mvc:annotation-driven />
</beans>
修改web.xml,将spring添加进去:
<?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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>SpringDataJPA</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
下面开始编写代码,注意注解不要忘记写,在本小节开始部分已经给出了包的层次结构。
实体User:
package com.anxpp.demo.core.entity;
public class User {
private Integer id;
private String name;
public User(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "id:"+id+",name:"+name;
}
}
dao层接口UserDao:
package com.anxpp.demo.core.dao;
import com.anxpp.demo.core.entity.User;
public interface UserDao {
User getUser(Integer id,String name);
}
dao层实现UserDaoImpl:
package com.anxpp.demo.core.dao.impl;
import org.springframework.stereotype.Repository;
import com.anxpp.demo.core.dao.UserDao;
import com.anxpp.demo.core.entity.User;
@Repository
public class UserDaoImpl implements UserDao{
@Override
public User getUser(Integer id, String name) {
return new User(id, name);
}
}
service层接口UserService:
package com.anxpp.demo.core.service;
import com.anxpp.demo.core.entity.User;
public interface UserService {
User getUser(Integer id, String name);
}
service层实现:
package com.anxpp.demo.core.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.anxpp.demo.core.dao.UserDao;
import com.anxpp.demo.core.entity.User;
import com.anxpp.demo.core.service.UserService;
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserDao userDao;
@Override
public User getUser(Integer id, String name) {
return userDao.getUser(id, name);
}
}
controller层DemoController:
package com.anxpp.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.anxpp.demo.core.service.UserService;
@Controller
@RequestMapping("/")
public class demoController {
@Autowired
UserService userService;
@RequestMapping("/")
@ResponseBody
public String index(){
return "index";
}
@RequestMapping("/getuser")
@ResponseBody
public String getUser(Integer id, String name){
return userService.getUser(id, name).toString();
}
}
这是还不能直接Run On Server,因为jar包不会被一同发布,我们需要如下配置:
右键工程选择属性,按下图配置:
这时候就可以运行测试了,效果如下:
到这里,我们还没有操作数据库的。
4、添加返回Json格式数据支持
现在,我们常使用json作为数据传输的格式,下面就为SpringMVC添加返回json的支持
首先添加jar包:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.5.0</version>
</dependency>
然后改写getUser()方法如下:
@RequestMapping("/getuser")
@ResponseBody
public Map<String, Object> getUser(Integer id, String name){
Map<String, Object> map = new HashMap<String, Object>();
map.put("state", "success");
map.put("data", userService.getUser(id, name));
return map;
}
重新运行后访问效果如下:
此时,就可以返回json数据了。
5、配置静态资源访问
通常情况下,WEB-INF目录下的资源,我们是无法直接访问的,如果我们的网站是html+ajax构成的,那么就可以在WEB-INF之外新建html的目录,并为web.xml配置默认的过滤器,不过注意要放到SpingMVC过滤器之前:
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
如果一定要访问WEB-INF目录内的资源,通过查阅Spring官方文档,发现有两种方式
1、手写一个资源映射器:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/public-resources/")
.setCacheControl(CacheControl.maxAge(1, TimeUnit.HOURS).cachePublic());
}
}
可以看到,还可以设置缓存时间的,而更简单的方式,就是xml配置:
<mvc:resources mapping="/resources/**" location="/public-resources/">
<mvc:cache-control max-age="3600" cache-public="true"/>
</mvc:resources>
也可以加上下面的这个:
<!-- 对静态资源文件的访问,将无法mapping到Controller的path交给default servlet handler处理-->
<mvc:default-servlet-handler />
6、乱码解决
我们通常使用ajax提交请求,但也常用地址栏直接测试。请求提交分get和post。
使用post提交请求是,一般是不会出现中文乱码的,但是如果确实出现了乱码,可以通过在web.xml添加一个编码过滤器解决:
<filter>
<filter-name>CharacterEncoding</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>CharacterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
上面只能解决post的中文乱码,对于get(含浏览器地址栏直接提交方式),我们需要修改tomcat配置,在conf目录下的server.xml中找到并如下修改:
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>
如果我们只是测试,项目并没有部署,可以直接在eclipse中的server下,找到server.xml,做出上面一样的改动即可:
7、整合SpringDataJPA+Hibernate
你可以通过这篇文字了解JPA:JPA规范介绍及实例(Java数据持久化解决方案)
SpringDataJPA也正是这样一种轻量级的解决方案,而首选的Hibernate就实现了JPA。
首先还是jar包,SpringDataJPA的jar包,在之前整合Spring时已经一并加入,下面是Hibernate(和mysql驱动)的jar包.
<!-- 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>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
统一管理的版本为:
<!-- hibernate 版本号 -->
<hibernate.version>5.1.0.Final</hibernate.version>
添加Jpa的配置文件persistence.xml到META-INF目录下,本文介绍时数据库使用MySQL。并添加如下内容:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="demo" transaction-type="RESOURCE_LOCAL">
<!-- provider>org.eclipse.persistence.jpa.PersistenceProvider</provider -->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.ninelephas.meerkat.pojo.User</class>
<!-- MYSql 的连接 -->
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.url" value="jdbc:mysql://127.0.0.1:3306/demo?createDatabaseIfNotExist=true" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.password" value="root" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
</properties>
</persistence-unit>
</persistence>
Spring配置文件applicationContext.xml中增加JPA支持后的完整内容:
<?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:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
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-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<!-- 开启IOC注解扫描 -->
<context:component-scan base-package="com.anxpp.demo" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true" />
<property name="database" value="MYSQL" />
</bean>
</property>
<property name="persistenceUnitName" value="demo" />
</bean>
<!-- 开启MVC注解扫描 -->
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="viewResolvers">
<list>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".html" />
</bean>
</list>
</property>
<!-- 用于将对象转换为 JSON -->
<property name="defaultViews">
<list>
<bean
class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />
</list>
</property>
</bean>
<!-- 对静态资源文件的访问,将无法mapping到Controller的path交给default servlet handler处理 -->
<mvc:default-servlet-handler />
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- 启用 annotation事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- 配置Spring Data JPA扫描目录 -->
<jpa:repositories base-package="com.anxpp.demo" />
</beans>
修改实体:
package com.anxpp.demo.core.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
public User() {
}
public User(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "id:"+id+",name:"+name;
}
}
可以删掉dao层实现了,我们记住将dao层接口继承自强大的JpaRepository:
public interface UserDao extends JpaRepository<User, Serializable>{
User findById(Integer id);
}
是不是看上去特别简洁,而且都不需要写实现的,SpringDataJPA会自动帮我们完成。
修改service层接口:
package com.anxpp.demo.core.service;
import java.util.List;
import com.anxpp.demo.core.entity.User;
public interface UserService {
User findById(Integer id);
User save(String name);
List<User> findAll();
}
修改service层实现:
package com.anxpp.demo.core.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.anxpp.demo.core.dao.UserDao;
import com.anxpp.demo.core.entity.User;
import com.anxpp.demo.core.service.UserService;
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserDao userDao;
@Override
public User findById(Integer id) {
return userDao.findById(id);
}
@Override
public User save(String name) {
return userDao.save(new User(name));
}
@Override
public List<User> findAll() {
return userDao.findAll();
}
}
修改controller,提供多个测试接口:
package com.anxpp.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.anxpp.demo.core.service.UserService;
@Controller
@RequestMapping("/")
public class demoController {
@Autowired
UserService userService;
@RequestMapping("/")
@ResponseBody
public String index(){
return "index";
}
@RequestMapping("/info")
public String info(){
return "info";
}
@RequestMapping("/findall")
@ResponseBody
public Map<String, Object> getUser(){
Map<String, Object> map = new HashMap<String, Object>();
map.put("state", "success");
map.put("data", userService.findAll());
return map;
}
@RequestMapping("/findbyid")
@ResponseBody
public Map<String, Object> findById(Integer id){
Map<String, Object> map = new HashMap<String, Object>();
map.put("state", "success");
map.put("data", userService.findById(id));
return map;
}
@RequestMapping("/add")
@ResponseBody
public Map<String, Object> save(String name){
Map<String, Object> map = new HashMap<String, Object>();
map.put("state", "success");
map.put("data", userService.save(name));
return map;
}
}
运行效果:
那么,如果需要添加一个查找id大于指定值的指定姓氏的数据呢?
如果是SQL,我们会这样写(?表示参数):
SELECT * FROM user WHERE id>? AND name like '?%';
但是这里,我们连SQL(或者HQL)都可以不用写,直接在dao层接口添加一个方法即可:
List<User> findByIdGreaterThanAndNameLike(Integer id,String name);
你不需要怀疑,上面的方法执行偏偏就是能成功(注意:service实现的使用,调用该方法记得name+"%")!
以上所述是小编给大家介绍的从最基本的Java工程搭建SpringMVC+SpringDataJPA+Hibernate的相关知识,希望对大家有所帮助,如果大家想了解更多资讯敬请关注网站!
以上是 从最基本的Java工程搭建SpringMVC+SpringDataJPA+Hibernate 的全部内容, 来源链接: utcz.com/p/209553.html