從最根本的Java工程搭建SpringMVC+SpringDataJPA+Hibernate。本站提示廣大學習愛好者:(從最根本的Java工程搭建SpringMVC+SpringDataJPA+Hibernate)文章只能為提供參考,不一定能成為您想要的結果。以下是從最根本的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的相干常識,願望對年夜家有所贊助,假如年夜家想懂得更多資訊敬請存眷網站!