从最基本的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核心包 --> <dependency> <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的相关知识,希望对大家有所帮助,如果大家想了解更多资讯敬请关注网站!