Intelligent sales system

1. Project construction preparation

1. Build Maven web project

2. Import the jar package required by the project

<?xml version="1.0" encoding="UTF-8"?>

<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.xwq</groupId>
  <artifactId>aisell</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>aisell Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>
  <!-- Set version number-->
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <org.springframework.version>4.2.5.RELEASE</org.springframework.version>
    <org.hibernate.version>4.3.8.Final</org.hibernate.version>
    <spring-data-jpa.version>1.9.0.RELEASE</spring-data-jpa.version>
    <com.fasterxml.jackson.version>2.5.0</com.fasterxml.jackson.version>
    <org.slf4j.version>1.6.1</org.slf4j.version>
  </properties>
  <dependencies>
    <!-- Spring Support package -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <!--Code generator template support package-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${org.springframework.version}</version>
      <scope>test</scope>
    </dependency>
    <!-- Introduce web Front end support -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <!-- SpringMCV Upload needs to use io package-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-io</artifactId>
      <version>1.3.2</version>
    </dependency>
    <!-- Package for file upload -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.2.2</version>
    </dependency>
    <!-- SpringMVC Of json Support package -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>${com.fasterxml.jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>${com.fasterxml.jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${com.fasterxml.jackson.version}</version>
    </dependency>
    <!-- hibernate Support package -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>${org.hibernate.version}</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>${org.hibernate.version}</version>
    </dependency>
    <!-- SpringData Support package -->
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-jpa</artifactId>
      <version>${spring-data-jpa.version}</version>
    </dependency>
    <!-- SpringData Extension package -->
    <dependency>
      <groupId>com.github.wenhao</groupId>
      <artifactId>jpa-spec</artifactId>
      <version>3.1.1</version>
      <!-- Remove all dependence -->
      <exclusions>
        <exclusion>
          <groupId>*</groupId>
          <artifactId>*</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.2.2</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.6</version>
    </dependency>

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.5</version>
    </dependency>
    <!-- Test package -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <!-- this scope It can only be used in compilation and test, and has no transitivity. Indicates that this is not added when running jar file -->
      <scope>provided</scope>
    </dependency>
    <!-- log file -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${org.slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${org.slf4j.version}</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.14</version>
    </dependency>
    <!-- Code generator template technology -->
    <dependency>
      <groupId>org.apache.velocity</groupId>
      <artifactId>velocity</artifactId>
      <version>1.6</version>
    </dependency>
    <!-- shiro Support package -->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-all</artifactId>
      <version>1.4.0</version>
      <type>pom</type>
    </dependency>
    <!-- shiro And Spring Integration package -->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-spring</artifactId>
      <version>1.4.0</version>
    </dependency>
    <!-- poi Supportive jar package -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>3.11</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>3.11</version>
    </dependency>
    <!-- Picture compression -->
    <!-- thumbnail -->
    <dependency>
      <groupId>net.coobird</groupId>
      <artifactId>thumbnailator</artifactId>
      <version>0.4.6</version>
    </dependency>
    <!-- Scheduled scheduling -->
    <dependency>
      <groupId>quartz</groupId>
      <artifactId>quartz</artifactId>
      <version>1.5.2</version>
    </dependency>
    <!-- Mail Support -->
    <dependency>
      <groupId>javax.mail</groupId>
      <artifactId>mail</artifactId>
      <version>1.4.1</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
        <version>8.1.15.v20140411</version>
        <configuration>
          <stopPort>9966</stopPort>
          <stopKey>foo</stopKey>
          <webAppConfig>
            <contextPath>/</contextPath>
          </webAppConfig>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

3. Configure the spring configuration file

<?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:tx="http://www.springframework.org/schema/tx"
       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.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/tx
         http://www.springframework.org/schema/tx/spring-tx.xsd
         http://www.springframework.org/schema/data/jpa
         http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

    <!--Component scan-->
    <!-- Can handle@Repository, @Service, and @Controller,@Autowired,@PersistenceContext annotation-->
    <context:component-scan base-package="com.xwq.service" />
    <!-- Load jdbc.properties -->
    <context:property-placeholder location="classpath:jdbc.properties" />
    <!--Configure connection pool-->
    <!-- destroy-method="close current bean When destroying, it will call close Method, close connection" -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" >
        <!-- Properties required for dependency injection connection pool,jdbc Four attributes -->
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <!--maxActive: Maximum number of connections -->
        <property name="maxActive" value="150" />
        <!--minIdle: Minimum free connection -->
        <property name="minIdle" value="5" />
        <!--maxIdle: Maximum free connection -->
        <property name="maxIdle" value="20" />
        <!--initialSize: Initialize connection -->
        <property name="initialSize" value="30" />
        <!-- Used to configure automatic connection after database disconnection. -->
        <!-- Whether to print when the connection is leaked -->
        <property name="logAbandoned" value="true" />
        <!--removeAbandoned: Whether to automatically recycle the timeout connection -->
        <property name="removeAbandoned" value="true" />
        <!--removeAbandonedTimeout: Timeout time(In seconds) -->
        <property name="removeAbandonedTimeout" value="10" />
        <!--maxWait: Timeout wait time in milliseconds 1000 equals 60 seconds -->
        <property name="maxWait" value="1000" />
        <!-- Time value to sleep during idle connection collector thread run,In Milliseconds . -->
        <property name="timeBetweenEvictionRunsMillis" value="10000" />
        <!-- On every idle connection the recycler thread(If there is)Number of connections checked at run time -->
        <property name="numTestsPerEvictionRun" value="10" />
        <!-- 1000 * 60 * 30 Connections remain idle in the pool without being idle connection collector threads -->
        <property name="minEvictableIdleTimeMillis" value="10000" />
        <property name="validationQuery" value="SELECT NOW() FROM DUAL" />
    </bean>

    <!--To configure entityManagerFactory-->
    <!-- org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter Introducing default entityManagerFactory Name -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <!--injection DataSource-->
        <property name="dataSource" ref="dataSource"/>
        <!--2.Which package to scan from@Entity,domain package-->
        <property name="packagesToScan" value="com.xwq.domain" />
        <!-- 3.To configure JPA Implementation -->
        <!--jpa Adapter-->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <!--dialect-->
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
                <!--Table creation (table creation strategy) true->update  false->Do nothing)-->
                <property name="generateDdl" value="false"/>
                <!--Whether to display sql-->
                <property name="showSql" value="true"/>
            </bean>
        </property>
    </bean>
    
    <!--Configuration transaction-->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>
    <!-- Configure support for transactions(Support adding transactions with annotations)It will find one by default. transactionManager Of bean-->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <!-- Spring Data Jpa To configure *-->
    <!-- base-package:Scanned package -->
    <jpa:repositories base-package="com.xwq.repository" transaction-manager-ref="transactionManager"
                      entity-manager-factory-ref="entityManagerFactory" />
</beans>

4. Configure db.properties

5. Create a domain and extract the parent class

Because the domain has id attribute, and in order to facilitate future expansion of functions, extract the parent class, and use @ MappedSuperclass to indicate that this is a parent class.

@MappedSuperclass
public class BaseDomain {
    @Id
    @GeneratedValue
    protected Long id;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
}

2. Use of springdatajpa

1.pom.xml configuration

  • 1. Import of basic SSJ - 2.SpringDataJpa
<dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-jpa</artifactId>
      <version>${spring-data-jpa.version}</version>
 </dependency>
2. Basic configuration of springdatajpa
(1) configure the corresponding spring data JPA
<jpa:repositories base-package="cn.itsource.aisell.repository"
            entity-manager-factory-ref="entityManagerFactory"
            transaction-manager-ref="transactionManager"
    ></jpa:repositories>
(2) inherit jparepository (specify domain type and primary key type)
interface EmployeeRepository extends JpaRepository<Employee,Long>, JpaSpecificationExecutor<Employee>
(3) complete corresponding CRUD
employeeRepository.findAll();
employeeRepository.findOne(Long id);
employeeRepository.save(object); //Add or modify
employeeRepository.delete(id/object);
employeeRepository.findAll(Pageable) -> paging
	Pageable pageable = new PageRequest(0, 5); //0 is the first page
employeeRepository.findAll(Sort) -> sort
	Sort sort = new Sort(Sort.Direction.DESC,"username");

If you want to combine paging and sorting: (transfer sorting objects to paging)

new PageRequest(0, 5,sort);
(4) advanced query
①. Name rule (define the method according to the specification, and SpringDataJpa will automatically proxy the implementation interface)
findByUsername(String username) //Query username =?
findByUsernameLike(String username) //username like ?
findByUsernameLikeAndEmailLike(String username,String email)  // username like ? and email like ?
②. Query annotation
//jpql
@Query("select o from Employee o where o.name like ?1")
@Query("select o from Employee o where o.name like :name")
//Native sql
@Query(nativeQuery = true,value="select * from employee")
(5) advanced query and paging
①.JpaSpecificationExecutor

You can complete the function without writing SQL
1. Our Repository inherits jpaspecification executor

EmployeeRepository extends JpaRepository<Employee,Long>,JpaSpecificationExecutor<Employee>

2.findAll query method

employeeRepository.findAll(Specification<T> spec)
    employeeRepository.findAll(Specification<T> spec,Pageable pageable)
    new Specification<Employee>{
        //Root: (root, table) get field  
        //query:where,group by ,order by...
        //cb: conditional judgment (one or more)
         @Override
        public Predicate toPredicate(Root<Employee> root, 
                                    CriteriaQuery<?> query, 
                                    CriteriaBuilder cb) {
            Path path = root.get("username");//Get the field to query
            Predicate p = cb.like(path, "%1%");//like stands for fuzzy query, followed by its condition value
            return p;
        }
    }
2.jpa-spec
<dependency>
    <groupId>com.github.wenhao</groupId>
    <artifactId>jpa-spec</artifactId>
    <version>3.1.0</version>
</dependency>
//First parameter: true - > enable conditional filtering
//Second parameter: attributes to be filtered
//The third parameter: filter condition? Corresponding value
Specification<Person> specification = Specifications.<Person>and()
            .eq(StringUtils.isNotBlank(request.getName()), "name", name)
            .gt(Objects.nonNull(request.getAge()), "age", 18)
            .build();

Keywords: Spring Apache Hibernate Maven

Added by johnrcornell on Sat, 02 Nov 2019 17:06:09 +0200