美文网首页web程序员Java学习笔记
J2EE项目系列(三)--Spring Data JPA+Spr

J2EE项目系列(三)--Spring Data JPA+Spr

作者: JackFrost_fuzhu | 来源:发表于2017-03-21 20:53 被阅读358次

    好久没给大家弄Java后端项目系列了,因为接了Java后端外包以及学习一些后端优化的东西。而现在开始慢慢在这个系列的(三)逐渐把后端外包的一些有价值的东西分享给大家,并且自己也总结一遍嘛。


    文章结构:(1)项目环境搭建;(2)简单业务逻辑测试框架;(3)项目配置注意点;(4)快速开发上手技巧;


    一、项目环境搭建:

    项目框架:Spring Data JPA+Spring+SpringMVC+Maven+JDK1.7+Tomcat7.0

    使用IDEA开发

    (1)Maven构建:

    <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.0</modelVersion>
      <groupId>com.fuzhu</groupId>
      <artifactId>springdatajpa</artifactId>
      <packaging>war</packaging>
      <version>1.0-SNAPSHOT</version>
      <name>springdatajpa Maven Webapp</name>
      <url>http://maven.apache.org</url>
    
      <properties>
    
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    
        <maven.build.timestamp.format>yyyyMMdd'T'HHmmss</maven.build.timestamp.format>
        <buildNumber>${maven.build.timestamp}</buildNumber>
    
        <maven.compiler.target>1.7</maven.compiler.target>
        <maven.compiler.source>1.7</maven.compiler.source>
    
        <java-version>1.7</java-version>
    
        <version-springframework>4.0.4.RELEASE</version-springframework>
        <version-slf4j>1.6.6</version-slf4j>
        <version-hibernate.validator>5.0.1.Final</version-hibernate.validator>
        <version-hibernate.jpa>1.0.1.Final</version-hibernate.jpa>
        <version-hibernate>4.2.6.Final</version-hibernate>
        <mysql.version>5.1.35</mysql.version>
    
      </properties>
    
    
      <dependencies>
        <!-- Spring MVC -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>${version-springframework}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>${version-springframework}</version>
        </dependency>
        <!-- spring 表达式语言 -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-expression</artifactId>
          <version>${version-springframework}</version>
        </dependency>
        <!-- 核心工具包 -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>${version-springframework}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>${version-springframework}</version>
          <exclusions>
            <!-- Exclude Commons Logging in favor of SLF4j -->
            <exclusion>
              <groupId>commons-logging</groupId>
              <artifactId>commons-logging</artifactId>
            </exclusion>
          </exclusions>
        </dependency>
    
        <!-- spring-context 的扩展支持,用于 MVC 方面 -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context-support</artifactId>
          <version>${version-springframework}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aop</artifactId>
          <version>${version-springframework}</version>
        </dependency>
        <!-- springIoC(依赖注入)的基础实现 -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-beans</artifactId>
          <version>${version-springframework}</version>
        </dependency>
        <!-- Spring事务支持 -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-tx</artifactId>
          <version>${version-springframework}</version>
        </dependency>
        <!-- spring 对Junit 等测试框架的简单封装 -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>${version-springframework}</version>
        </dependency>
        <!--hibernate的包-->
        <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-core</artifactId>
          <version>${version-hibernate}</version>
        </dependency>
        <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-entitymanager</artifactId>
          <version>${version-hibernate}</version>
          <exclusions>
            <exclusion>
              <artifactId>cglib</artifactId>
              <groupId>cglib</groupId>
            </exclusion>
            <exclusion>
              <artifactId>dom4j</artifactId>
              <groupId>dom4j</groupId>
            </exclusion>
          </exclusions>
        </dependency>
        <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-validator</artifactId>
          <version>${version-hibernate.validator}</version>
        </dependency>
        <dependency>
          <groupId>org.hibernate.javax.persistence</groupId>
          <artifactId>hibernate-jpa-2.0-api</artifactId>
          <version>${version-hibernate.jpa}</version>
        </dependency>
        <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-ehcache</artifactId>
          <version>${version-hibernate}</version>
        </dependency>
    
        <!-- Spring data jpa -->
        <dependency>
          <groupId>org.springframework.data</groupId>
          <artifactId>spring-data-jpa</artifactId>
          <version>1.6.2.RELEASE</version>
        </dependency>
    
        <!-- AspectJ 切面-->
        <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjrt</artifactId>
          <version>1.6.10</version>
        </dependency>
    
        <!-- Logging -->
        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>${version-slf4j}</version>
        </dependency>
        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>jcl-over-slf4j</artifactId>
          <version>${version-slf4j}</version>
          <scope>runtime</scope>
        </dependency>
        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>${version-slf4j}</version>
          <scope>runtime</scope>
        </dependency>
        <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>1.2.15</version>
          <exclusions>
            <exclusion>
              <groupId>javax.mail</groupId>
              <artifactId>mail</artifactId>
            </exclusion>
            <exclusion>
              <groupId>javax.jms</groupId>
              <artifactId>jms</artifactId>
            </exclusion>
            <exclusion>
              <groupId>com.sun.jdmk</groupId>
              <artifactId>jmxtools</artifactId>
            </exclusion>
            <exclusion>
              <groupId>com.sun.jmx</groupId>
              <artifactId>jmxri</artifactId>
            </exclusion>
          </exclusions>
          <scope>runtime</scope>
        </dependency>
        <!-- logging end-->
        <!-- @Inject -->
        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>servlet-api</artifactId>
          <version>3.0-alpha-1</version>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>javax.servlet.jsp</groupId>
          <artifactId>jsp-api</artifactId>
          <version>2.2</version>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>jstl</artifactId>
          <version>1.2</version>
        </dependency>
    
        <!-- druid dataSource -->
        <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid</artifactId>
          <version>1.0.0</version>
        </dependency>
    
        <!--mysql -->
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>${mysql.version}</version>
        </dependency>
    
        <!-- Apache Commons Dependencies -->
        <dependency>
          <groupId>org.apache.commons</groupId>
          <artifactId>commons-lang3</artifactId>
          <version>3.3.2</version>
        </dependency>
    
        <dependency>
          <groupId>commons-fileupload</groupId>
          <artifactId>commons-fileupload</artifactId>
          <version>1.3.1</version>
        </dependency>
    
        <dependency>
          <groupId>org.apache.commons</groupId>
          <artifactId>commons-digester3</artifactId>
          <version>3.2</version>
        </dependency>
    
        <dependency>
          <groupId>commons-io</groupId>
          <artifactId>commons-io</artifactId>
          <version>2.4</version>
        </dependency>
    
        <dependency>
          <groupId>org.apache.commons</groupId>
          <artifactId>commons-exec</artifactId>
          <version>1.2</version>
        </dependency>
    
        <dependency>
          <groupId>commons-beanutils</groupId>
          <artifactId>commons-beanutils</artifactId>
          <version>1.9.1</version>
        </dependency>
    
        <dependency>
          <groupId>commons-codec</groupId>
          <artifactId>commons-codec</artifactId>
          <version>1.9</version>
        </dependency>
        <!--common end-->
        <dependency>
          <groupId>cglib</groupId>
          <artifactId>cglib</artifactId>
          <version>2.2.2</version>
        </dependency>
    
        <!--fastjson-->
        <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>fastjson</artifactId>
          <version>1.2.5</version>
        </dependency>
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-core</artifactId>
          <version>2.1.0</version>
        </dependency>
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.1.0</version>
        </dependency>
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-annotations</artifactId>
          <version>2.1.0</version>
        </dependency>
    
        <!-- junit测试的包-->
        <dependency>
          <groupId>org.hamcrest</groupId>
          <artifactId>hamcrest-core</artifactId>
          <version>1.3</version>
          <scope>test</scope>
        </dependency>
        <dependency>
          <groupId>org.hamcrest</groupId>
          <artifactId>hamcrest-library</artifactId>
          <version>1.3</version>
          <scope>test</scope>
        </dependency>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.12</version>
          <scope>test</scope>
        </dependency>
    
    
      </dependencies>
    <!-- 固定版本1.7-->
      <build>
        <finalName>springdatajpa</finalName>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
              <source>1.7</source>
              <target>1.7</target>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>
    

    (2).spring配置文件:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans  xmlns="http://www.springframework.org/schema/beans"
        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
        xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
        xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
        <!--扫描资源文件-->
        <context:property-placeholder location="classpath:database.properties" ignore-unresolvable="true"/>
        <!--Druid数据源-->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
            <property name="driverClassName" value="${database.driverClassName}"/>
            <property name="url" value="${database.url}" />
            <property name="username" value="${database.username}" />
            <property name="password" value="${database.password}" />
            <!-- 申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能 -->
            <property name="testOnBorrow" value="false" />
            <property name="testOnReturn" value="false" />
            <!-- 申请连接的时候检测 -->
            <property name="testWhileIdle" value="false" />
            <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
            <property name="timeBetweenEvictionRunsMillis" value="1800000" />
            <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
            <property name="minEvictableIdleTimeMillis" value="1800000" />
            <property name="defaultAutoCommit" value="false" />
    
        </bean>
    
    
        <!-- 指定事务管理器,JPA使用JpaTransactionManager事务管理器实现. -->
        <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
            <property name="entityManagerFactory" ref="entityManagerFactory" />
        </bean>
    
        <!-- 指定JPA实现 -->
        <bean id="jpaVendorAdapter"
            class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="false" />
        </bean>
    
        <!-- 适用于所有环境的FactoryBean,能全面控制EntityManagerFactory配置,如指定Spring定义的DataSource等等. -->
        <bean id="entityManagerFactory"
            class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
            <!-- 指定持久化单元名字,即JPA配置文件中指定的 -->
            <property name="persistenceUnitName" value="com.ima" />
            <!-- 见上 -->
            <property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
            <!-- 见上 -->
            <property name="dataSource" ref="dataSource" />
        </bean>
    
    <!-- 映射jpa接口-->
        <jpa:repositories base-package="com.ima.repository" />
    
        <!-- 开启事务管理注解 -->
        <tx:annotation-driven transaction-manager="transactionManager"/>
    
    
    </beans>
    
    

    (3).springMVC的配置:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
           http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
    
        <!-- 开启SpringMVC注解 -->
        <mvc:annotation-driven />
    
        <!-- 只扫描Controller 注解 -->
        <context:component-scan base-package="com.ima.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="resourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/views/"/>
            <property name="suffix" value=".jsp"/>
            <property name="contentType" value="text/html;charset=UTF-8"/>
        </bean>
        <!-- 用于返回json格式 -->
        <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>application/x-www-form-urlencoded;charset=UTF-8</value>
                </list>
            </property>
        </bean>
    
        <!--上传文件配置-->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <property name="defaultEncoding" value="utf-8"/>
            <property name="maxUploadSize" value="10485760"/>
            <property name="maxInMemorySize" value="40960"/>
        </bean>
    
    
        <mvc:annotation-driven>
            <mvc:message-converters register-defaults="true">
                <!--字符串编码转换-->
                <bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
                    <constructor-arg value="UTF-8"/>
                </bean>
            </mvc:message-converters>
        </mvc:annotation-driven>
    </beans>
    
    

    (4).数据源的配置:

    database.url=jdbc:mysql://127.0.0.1:3306/aidou?useUnicode=true&characterEncoding=utf8
    database.username=root
    database.password=751197996
    database.driverClassName=com.mysql.jdbc.Driver
    

    (5).log4j的日志配置(见源码)

    (6).JPA的配置包,指定持久化单元:

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
        <persistence-unit name="com.ima" transaction-type="RESOURCE_LOCAL">
    
            <!--ENABLE_SELECTIVE[(默认和推荐值):实体不缓存,除非明确标记为可缓存的。] DISABLE_SELECTIVE[实体缓存,除非明确标记为不缓存] NONE[无缓存] ALL[全部缓存]-->
            <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
            <properties>
                <!-- 使用MySQL方言 -->
                <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
    
                <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
                <property name="hibernate.connection.url" value="jdbc:mysql:///aidou" />
                <property name="hibernate.connection.username" value="root" />
                <property name="hibernate.connection.password" value="751197996" />
    
                <property name="hibernate.connection.charSet" value="UTF-8" />
                <!-- 自动输出schema创建DDL语句 -->
                <property name="hibernate.hbm2ddl.auto" value="update" />
                <!-- 显示SQL语句 -->
                <property name="hibernate.show_sql" value="true" />
                <!-- 在显示SQL语句时格式化语句 -->
                <property name="hibernate.format_sql" value="true" />
                <property name="hibernate.use_sql_comments" value="true" />
    
                 <!--org.hibernate.cache.EhCacheRegionFactory -->
                <!-- Enable Batching -->
                <property name="hibernate.jdbc.batch_size" value="20" />
                <property name="hibernate.default_batch_fetch_size" value="10" />
    
                <!-- Hibernate二级缓存相关配置 -->
                <!-- 开启二级缓存 -->
                <property name="hibernate.cache.use_second_level_cache" value="true" />
                <!-- 打开Hibernate查询缓存 -->
                <property name="hibernate.cache.use_query_cache" value="true" />
                <!-- 配置缓存提供者 -->
                <property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory" />
                <property name="hibernate.generate_statistics" value="true" />
                
            </properties>
        </persistence-unit>
    </persistence>
    

    (7).web.xml配置

    <!DOCTYPE web-app PUBLIC
            "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
            "http://java.sun.com/dtd/web-app_2_3.dtd" >
    
    <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>Archetype Created Web Application</display-name>
      <!-- Spring 配置 -->
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:META-INF/spring/spring-jpa.xml</param-value>
      </context-param>
      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      <!-- log4j 系统日志-->
      <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:META-INF/log4j.properties</param-value>
      </context-param>
      <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
      </listener>
    
      <!-- 使用spring Encoding,设置为UTF-8 -->
      <filter>
        <filter-name>Set Character Encoding</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>Set Character Encoding</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
    
      <!-- Spring MVC 启动配置 -->
      <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:META-INF/springmvc/spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
      </servlet-mapping>
    
      <filter>
        <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
        <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
        <init-param>
          <!-- 指定org.springframework.orm.jpa.LocalEntityManagerFactoryBean在spring配置文件中的名称,默认值为entityManagerFactory
              如果LocalEntityManagerFactoryBean在spring中的名称不是entityManagerFactory,该参数一定要指定,否则会出现找不到entityManagerFactory的例外 -->
          <param-name>entityManagerFactoryBeanName</param-name>
          <param-value>entityManagerFactory</param-value>
        </init-param>
      </filter>
      <filter-mapping>
        <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
    
    
    
    
      <!-- Druid,监控数据库,以及WEB访问连接信息 -->
      <!--根据配置中的url-pattern来访问内置监控页面,如果是上面的配置,内置监控页面的首页是/druid/index.html-->
      <filter>
        <filter-name>DruidWebStatFilter</filter-name>
        <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
        <init-param>
          <param-name>exclusions</param-name>
          <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
        </init-param>
        <init-param>
          <param-name>sessionStatMaxCount</param-name>
          <param-value>1000</param-value>
        </init-param>
        <init-param>
          <param-name>sessionStatEnable</param-name>
          <param-value>false</param-value>
        </init-param>
      </filter>
      <filter-mapping>
        <filter-name>DruidWebStatFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
    
      <servlet>
        <servlet-name>DruidStatView</servlet-name>
        <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
        <init-param>
          <!-- 允许清空统计数据 -->
          <param-name>resetEnable</param-name>
          <param-value>true</param-value>
        </init-param>
        <init-param>
          <!-- 用户名 -->
          <param-name>loginUsername</param-name>
          <param-value>druid</param-value>
        </init-param>
        <init-param>
          <!-- 密码 -->
          <param-name>loginPassword</param-name>
          <param-value>druid</param-value>
        </init-param>
      </servlet>
      <servlet-mapping>
        <servlet-name>DruidStatView</servlet-name>
        <url-pattern>/druid/*</url-pattern>
      </servlet-mapping>
    </web-app>
    

    这样就完成了工程的配置了!!!


    二、简单业务逻辑测试框架

    简单的bean:(为了偷懒就用JPA自动建表了,不过后面会给出sql,而且JPA自动建表有坑!!)

    //积分变化记录
    @Entity
    @Table(name = "i_dou_change")
    public class IDouChange {
        private Long id;
        //积分变化的类型,拉黑或者在线或者充值
        private String changeType;
        private Date createTime;
        //积分变化数
        private Integer iDouCount;
        //积分变化者
        private User user;
    
    
        public IDouChange() {
        }
    
        @Id
        @GeneratedValue
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
    
        @Column(name = "change_type")
        public String getChangeType() {
            return changeType;
        }
    
        public void setChangeType(String changeType) {
            this.changeType = changeType;
        }
    
        @Temporal(TemporalType.TIMESTAMP)
        @Column(name = "create_time",nullable=true,columnDefinition="timestamp default current_timestamp")
        public Date getCreateTime() {
            return createTime;
        }
    
        public void setCreateTime(Date createTime) {
            this.createTime = createTime;
        }
    
        @Column(name = "i_dou_count")
        public Integer getiDouCount() {
            return iDouCount;
        }
    
        public void setiDouCount(Integer iDouCount) {
            this.iDouCount = iDouCount;
        }
    //简单的多对一
        @JoinColumn(name="user_id")
        @ManyToOne(fetch= FetchType.LAZY)
        public User getUser() {
            return user;
        }
    
        public void setUser(User user) {
            this.user = user;
        }
    }
    
    

    对应的repository接口dao

    @Repository
    public interface AiDouChangeRepository extends JpaRepository<IDouChange, Long> {
        
    }
    
    

    对应的service

    @Service
    public class AiDouService {
        @Autowired
        private AiDouChangeRepository aiDouChangeRepository;
        public void save(IDouChange iDouChange){
            aiDouChangeRepository.save(iDouChange);
        }
     
    }
    
    

    写个测试的controller

    @RestController
    @RequestMapping("/user")
    public class UserController {
        @Autowired
        private UserService userService;
        @Autowired
        private AiDouService aiDouService;
    
    
        //test:
        @RequestMapping(value = "/test", method = {RequestMethod.GET, RequestMethod.POST}, produces = "text/html;charset=UTF-8")
        //测试嘛
        public String test(String type, Integer iDouCount )  {
            DTO dto = new DTO();
            IDouChange iDouChange = new IDouChange();
            iDouChange.setChangeType(type);
            iDouChange.setiDouCount(iDouCount);
            aiDouService.save(iDouChange);
            if (iDouChange == null) {
                dto.code = "-1";
                dto.msg = "Have bean registered";
                return JSON.toJSONString(dto);
            } else {
                return JSON.toJSONString(iDouChange);
            }
        }
    }
    

    然后??直接部署呀!!对应传参,测试成功咯!!!

    这里写图片描述

    一对多没实现关联,傻逼的插入就是这样的啦

    这里写图片描述

    三、项目配置注意点:

    这里写图片描述 这里写图片描述

    还有就是在web.xml中映射好spring文件以及springMVC文件

    四、快速开发上手技巧:

    (1)在一般项目时,使用这个框架Spring Data JPA+Spring+SpringMVC+Maven,快速映射dao层即可编写业务

    (2)接口文档工具,swagger+postman,让前端移动端更快速接入

    (3)数据库最好还是新建好导入,再用IDEA的persistence导入,这样的话,编码问题就不会出现太多。用IDEA的persistence导入姿势

    (4)虽然不建议用jpa自动建表,因为有编码问题,不懂的人,就尴尬了,要搞很久,这个系列的第三篇博客会讲解怎么解决这个的编码问题。


    源码下载:J2EE项目系列(三)--Spring Data JPA+Spring+SpringMVC+Maven快速开发(1)项目架构

    好了,J2EE项目系列(三)--Spring Data JPA+Spring+SpringMVC+Maven快速开发(1)项目架构讲完了。本博客是这个系列的第一篇,所以先讲下项目架构。另外,这个系列还有一些我在外包项目过程中做的优化,七牛云,云旺IM等使用,以及解决一些小bug等等技巧,我会尽快出完给大家,分享经验给大家。欢迎在下面指出错误,共同学习!!你的点赞是对我最好的支持!!

    更多内容,可以访问JackFrost的博客

    相关文章

      网友评论

        本文标题:J2EE项目系列(三)--Spring Data JPA+Spr

        本文链接:https://www.haomeiwen.com/subject/ljtnnttx.html