SSH(进阶) SpringDataJPA + SpringMVC 快速搭建企业框架

1、什么是JPA?

    JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。

    事实上,JPA并不是一项技术,而是一种标准,因为JPA只是一套接口,本身不能完成任何事情。JPA只是规范了Java持久化的官方标准。JPA有以下几个优点。

1、 可持久化Java对象。(JPA能够直接持久化复杂的Java对象,并能够使用JPQL语言进行复杂的查询)

2、 使用简单。(JPA使用注释(Annotation)定义Java对象与关系数据库之间的映射)

2、什么是SpringData?

    Spring Data是一个用于简化数据库访问,并支持云服务的开源框架。其主要目标是使得对数据的访问变得方便快捷,并支持map-reduce框架和云计算数据服务。 

    主要来看看Spring Data JPA提供的接口,也是Spring Data JPA的核心概念:

1、Repository:最顶层的接口,是一个空的接口,目的是为了统一所有Repository的类型,且能让组件扫描的时候自动识别。
2、CrudRepository :是Repository的子接口,提供CRUD的功能
3、PagingAndSortingRepository:是CrudRepository的子接口,添加分页和排序的功能

4、JpaRepository:是PagingAndSortingRepository的子接口,增加了一些实用的功能,比如:批量操作等。
5、JpaSpecificationExecutor:用来做负责查询的接口
6、Specification:是Spring Data JPA提供的一个查询规范,要做复杂的查询,只需围绕这个规范来设置查询条件即可

**在本篇文章我们主要是运用 JpaRespository 这个接口.**

3、搭建SpringDataJPA和SpringMVC框架

1、首先我们来看看项目结构:

SSH(进阶) SpringDataJPA + SpringMVC 快速搭建企业框架_第1张图片

a、新建Maven工程:打开eclipse ->file->new->project->Maven->Maven Project

SSH(进阶) SpringDataJPA + SpringMVC 快速搭建企业框架_第2张图片

选择 maven-archetype-webapp 下一步;

SSH(进阶) SpringDataJPA + SpringMVC 快速搭建企业框架_第3张图片

填Group Id 和 Artifact id,Group Id 是域名,Artifact id填项目名称就行了

b、项目建好之后就是导Maven包,这里我们引入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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0modelVersion>
    <groupId>com.ajie.wechatgroupId>
    <artifactId>ajie-wechatartifactId>
    <packaging>jarpackaging>
    <version>0.0.1-SNAPSHOTversion>
    <name>ajie-wechatname>
    <url>http://maven.apache.orgurl>

    <dependencies>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>3.8.1version>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>3.1.0version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>4.1.3.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>4.1.3.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-beansartifactId>
            <version>4.1.3.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webartifactId>
            <version>4.1.3.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>4.1.3.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aopartifactId>
            <version>4.1.3.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-txartifactId>
            <version>4.1.3.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
            <version>4.1.3.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-ormartifactId>
            <version>4.1.3.RELEASEversion>
        dependency>

        <dependency>
            <groupId>org.hibernategroupId>
            <artifactId>hibernate-coreartifactId>
            <version>4.3.11.Finalversion>
        dependency>
        <dependency>
            <groupId>org.hibernategroupId>
            <artifactId>hibernate-entitymanagerartifactId>
            <version>4.3.11.Finalversion>
        dependency>
        <dependency>
            <groupId>org.hibernategroupId>
            <artifactId>hibernate-ehcacheartifactId>
            <version>4.3.11.Finalversion>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.35version>
        dependency>
        <dependency>
            <groupId>commons-dbcpgroupId>
            <artifactId>commons-dbcpartifactId>
            <version>1.2.2version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-apiartifactId>
            <version>1.7.12version>
        dependency>
        <dependency>
            <groupId>com.jolboxgroupId>
            <artifactId>bonecpartifactId>
            <version>0.8.0.RELEASEversion>
        dependency>
        <dependency>
            <groupId>com.jolboxgroupId>
            <artifactId>bonecp-springartifactId>
            <version>0.8.0.RELEASEversion>
        dependency>
        <dependency>
            <groupId>com.jolboxgroupId>
            <artifactId>bonecp-providerartifactId>
            <version>0.8.0-alpha1version>
        dependency>
        <dependency>
            <groupId>taglibsgroupId>
            <artifactId>standardartifactId>
            <version>1.1.2version>
        dependency>
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>1.8.7version>
        dependency>
        <dependency>
            <groupId>cglibgroupId>
            <artifactId>cglib-nodepartifactId>
            <version>3.2.0version>
        dependency>
        <dependency>
            <groupId>commons-collectionsgroupId>
            <artifactId>commons-collectionsartifactId>
            <version>3.2.1version>
        dependency>
        <dependency>
            <groupId>antgroupId>
            <artifactId>antartifactId>
            <version>1.6.5version>
        dependency>
        <dependency>
            <groupId>org.apache.avrogroupId>
            <artifactId>avroartifactId>
            <version>1.7.7version>
        dependency>
        <dependency>
            <groupId>commons-beanutilsgroupId>
            <artifactId>commons-beanutilsartifactId>
            <version>1.9.2version>
        dependency>
        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
            <version>1.3.1version>
        dependency>
        <dependency>
            <groupId>commons-iogroupId>
            <artifactId>commons-ioartifactId>
            <version>2.4version>
        dependency>
        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-lang3artifactId>
            <version>3.4version>
        dependency>
        <dependency>
            <groupId>dom4jgroupId>
            <artifactId>dom4jartifactId>
            <version>1.6.1version>
        dependency>
        <dependency>
            <groupId>net.sf.ezmorphgroupId>
            <artifactId>ezmorphartifactId>
            <version>1.0.6version>
        dependency>
        <dependency>
            <groupId>org.freemarkergroupId>
            <artifactId>freemarkerartifactId>
            <version>2.3.23version>
        dependency>
        <dependency>
            <groupId>com.google.guavagroupId>
            <artifactId>guavaartifactId>
            <version>18.0version>
        dependency>
        <dependency>
            <groupId>org.javassistgroupId>
            <artifactId>javassistartifactId>
            <version>3.20.0-GAversion>
        dependency>
        <dependency>
            <groupId>org.jboss.logginggroupId>
            <artifactId>jboss-loggingartifactId>
            <version>3.3.0.Finalversion>
        dependency>
        
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.5.0version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-coreartifactId>
            <version>2.5.0version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-annotationsartifactId>
            <version>2.5.0version>
        dependency>
        
        <dependency>
            <groupId>org.springframework.datagroupId>
            <artifactId>spring-data-jpaartifactId>
            <version>1.7.1.RELEASEversion>
        dependency>

    dependencies>
    <build>
        <plugins>
            
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>2.3.2version>
                <configuration>
                    <source>1.7source>
                    <target>1.7target>
                    <encoding>utf8encoding>
                configuration>
            plugin>
        plugins>
        <finalName>ajie-wechatfinalName>
    build>
project>

右键项目run As -> MavenInstall,从Maven 仓库下载项目所需的依赖包 .

C、配置spring-mvc.xml 和 applicationContext.xml 和 Jdcb.properties 配置文件:

1、 applicationContext.xml的配置文件:


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    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.1.xsd
                    http://www.springframework.org/schema/tx 
                    http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
                    http://www.springframework.org/schema/aop 
                    http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
                    http://www.springframework.org/schema/context      
                    http://www.springframework.org/schema/context/spring-context-3.1.xsd
                    http://www.springframework.org/schema/cache 
                    http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
                    http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd 
                    http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd" 
                    default-lazy-init="true">

    
    <context:component-scan base-package="com.xiaoyu.jpa">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    context:component-scan>

    
    <context:property-placeholder location="/config/jdcb.properties" />


    
    <bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource"
        destroy-method="close">
        
        <property name="driverClass" value="${jdbc.driverClassName}" />
        
        <property name="jdbcUrl" value="${jdbc.url}" />
        
        <property name="username" value="${jdbc.username}" />
        
        <property name="password" value="${jdbc.password}" />
    bean>

    
    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" />
        
        <property name="packagesToScan" value="com.xiaoyu.jpa.model" />

        <property name="jpaProperties">
            <props>
                <prop key="hibernate.current_session_context_class">threadprop>
                <prop key="hibernate.hbm2ddl.auto">updateprop>
                <prop key="hibernate.show_sql">falseprop>
                <prop key="hibernate.format_sql">falseprop>

                
                <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategyprop>

            props>
        property>
    bean>

    
    <bean id="hibernateJpaVendorAdapter"
        class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <property name="databasePlatform" value="${hibernate.dialect}"/>
    bean>

    
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    bean>

    
    <jpa:repositories base-package="com.xiaoyu.jpa"  transaction-manager-ref="transactionManager" entity-manager-factory-ref="entityManagerFactory"/>

    
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
beans>

2、spring-mvc.xml 配置文件:


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation=" 
                http://www.springframework.org/schema/beans 
                http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
                http://www.springframework.org/schema/context 
                http://www.springframework.org/schema/context/spring-context-3.1.xsd 
                http://www.springframework.org/schema/mvc 
                http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd" >

    
    <mvc:annotation-driven />
    
    <context:component-scan base-package="com.xiaoyu.jpa.controller" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    context:component-scan>

    

    
    

    
    <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">    
        <property name="supportedMediaTypes">    
            <list>
                <value>application/x-www-form-urlencoded;charset=UTF-8value>
            list>
        property>
    bean>

     
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
         <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" />
            list>
        property>
    bean>

     
      
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        
        <property name="prefix" value="/" />
        <property name="suffix" value=".html" />
    bean>

    


    
    <mvc:resources location="/css/" mapping="/css/**" />

    <mvc:resources location="/images/" mapping="/images/**" />
    <mvc:resources location="/ATTACHMENT/" mapping="/ATTACHMENT/**" />

beans>

3、项目的 web.xml 文件:


<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">

  <display-name>Archetype Created Web Applicationdisplay-name>

  <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>/WEB-INF/spring/applicationContext.xmlparam-value>
    context-param>

       
      
    <listener>  
        <listener-class>org.springframework.web.util.IntrospectorCleanupListenerlistener-class>  
    listener>  

       
      
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>

    
    <filter>
        <filter-name>characterEncodingFilterfilter-name>
        <filter-class>
            org.springframework.web.filter.CharacterEncodingFilter
        filter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
        <init-param>
            <param-name>forceEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>characterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    
    
    <filter>
        <filter-name>hibernateFilterfilter-name>
        <filter-class>
            org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
        filter-class>
    filter>
    <filter-mapping>
        <filter-name>hibernateFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    
    <servlet-mapping>  
        <servlet-name>defaultservlet-name> 
        <url-pattern>*.jpgurl-pattern>    
    servlet-mapping> 
    <servlet-mapping>  
        <servlet-name>defaultservlet-name> 
        <url-pattern>*.pngurl-pattern>    
    servlet-mapping>     
    <servlet-mapping>  
        <servlet-name>defaultservlet-name> 
        <url-pattern>*.gifurl-pattern>    
    servlet-mapping> 
    <servlet-mapping>  
        <servlet-name>defaultservlet-name> 
        <url-pattern>*.woffurl-pattern>    
    servlet-mapping> 
    <servlet-mapping>  
        <servlet-name>defaultservlet-name> 
        <url-pattern>*.ttfurl-pattern>    
    servlet-mapping>          
    <servlet-mapping>  
        <servlet-name>defaultservlet-name> 
        <url-pattern>*.mapurl-pattern>    
    servlet-mapping>      
    <servlet-mapping>      
        <servlet-name>defaultservlet-name>   
        <url-pattern>*.jsurl-pattern>   
    servlet-mapping>  
    <servlet-mapping>       
        <servlet-name>defaultservlet-name>      
        <url-pattern>*.cssurl-pattern>     
    servlet-mapping>  
    <servlet-mapping>       
        <servlet-name>defaultservlet-name>      
        <url-pattern>*.htmlurl-pattern>     
    servlet-mapping>

    
    <servlet>
        <servlet-name>dispatcherServletservlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        servlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>/WEB-INF/spring/spring-mvc.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServletservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>

    <welcome-file-list>
        <welcome-file>/index.htmlwelcome-file>
    welcome-file-list>
web-app>

4、jdcb.properties 配置文件:

jdbc.driverClassName=com.mysql.jdbc.Driver

jdbc.url=jdbc\:mysql\://localhost\:3306/people?useUnicode\=true&characterEncoding\=UTF-8

jdbc.username=root

jdbc.password=123456

hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

BoneCP.idleConnectionTestPeriod=60

BoneCP.idleMaxAge=60

BoneCP.maxConnectionsPerPartition=5

BoneCP.minConnectionsPerPartition=1

BoneCP.partitionCount=3

BoneCP.acquireIncrement=2  

BoneCP.statementsCacheSize=0 

BoneCP.releaseHelperThreads=3

D、新建 Person.class 实体类、PersonDao接口、PersonService类、PersonController类:

1、新建Person实体类:

@Entity
@Table(name = "person")
public class Person implements Serializable {

    private static final long serialVersionUID = 7419229779731522702L;

    private int id;
    private String name;
    private int age;
    private int sex;

    public Person(){};

    @Id
    @Column(name="id",nullable=false,length=32,unique=true)
    @GenericGenerator(name="generator",strategy="uuid.hex")
    @GeneratedValue
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }


    @Column(name="name",nullable=false,length=32)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


    @Column(name="age",nullable=false,length=32)
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }


    @Column(name="sex",nullable=false,length=32)
    public int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

    public Person(int id, String name, int age, int sex) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", age=" + age + ", sex=" + sex + "]";
    }

2、新建PersonDao接口:

public interface PersonDao extends JpaRepository<Person,Integer> {

    @Query(value="From Person" )
    List findAllPersons();

    @Query(value="From Person where name = ?")
    Person findPersonByName(String name);

    //@Query(value="select * from person",nativeQuery = true)
    //List findAllPersons();
}

PersonDao接口主要实现 springdataJpa 的 JpaRepository

@Service
@Transactional
public class PersonService {


    @Autowired
    private PersonDao persondao;


    public String add(Person person){
        persondao.save(person);
        return "添加成功";
    }

    public String updatePerson(Person p){
        persondao.save(p);
        return "添加成功";
    }

    public Person findPersonById(int id ){
        return persondao.findOne(id);
    }

    public List findAllPersons(){
        return persondao.findAllPersons();
    }

    public Person findPersonByName(String name){
        return persondao.findPersonByName(name);
    }

4、PersonController类:

@Controller
@RequestMapping(value="/controller")
public class PersonController {

    @Autowired
    private PersonService personServcie; 

    @ResponseBody
    @RequestMapping(value="/savePerson")
    public String savePerson(){
        Person p = new Person();
        p.setId(3);
        p.setName("王五");
        p.setSex(20);
        String result = personServcie.add(p);
        return result;
    }

    @ResponseBody
    @RequestMapping(value="/findPerson")
    public Person findPerson(int id){
        System.out.println("已经进来了这里");
        Person p = personServcie.findPersonById(id);
        return p;
    }

    @ResponseBody
    @RequestMapping(value="/updatePerson")
    public Person updatePerson(int id){
        System.out.println("已经进来了这里");
        Person p = new Person();
        p = personServcie.findPersonById(id);
        p.setAge(20);
        p.setSex(0);
        personServcie.add(p);
        return p;
    }

    @ResponseBody
    @RequestMapping(value="/findAllPersons")
    public List findAllPersons(){
        return personServcie.findAllPersons();
    }


    @ResponseBody
    @RequestMapping(value="/findByName")
    public Person findByName(String name){
        return personServcie.findPersonByName("张三");
    }

启动项目然后访问 :
http://localhost:8080/quick4j/controller/findPerson?id=1

SSH(进阶) SpringDataJPA + SpringMVC 快速搭建企业框架_第4张图片

你可能感兴趣的:(JAVAEE技术博客)