springboot integration jpa project entry level demo

springboot integration jpa project entry level demo

preface

  • Simple basic entry level, no fragrance if you have a foundation!

1, Create an empty boot project

  • Just create it like a fool

2, Prepare the database, mainly MySQL

  • Create the test table and dog table for later use

3, Import dependency

  • The following dependencies, which will be used later, are posted directly

    org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-jpa mysql mysql-connector-java runtime org.projectlombok lombok 1.16.14 com.alibaba fastjson 1.2.76

4, Generate JPA entities

JPA automatically generates JPA entity class (idea).

5, JPA basic notes

  • @entity
  • @Table(name="table_name")
    This annotation is required when the current entity is different from its mapped database table name. If it is consistent, it is OK not to add it
  • @Id primary key
  • @GeneratedValue
    Generation strategy of primary key, for example: @ GeneratedValue(strategy = GenerationType.AUTO)
  • @Basic
    Represents the mapping of a simple attribute to the fields of the database table. For the getXXX() method without any annotation, the default is @ basic, which will map XXX to a column of the database
    That is, @ Basic is added by default if no annotation is added to the entity's get method (this annotation can be added or not)
  • @Column(name = "dog_name") maps the database field name
  • @Transient indicates that the attribute is not a mapping to the field of the database table. The ORM framework will ignore this attribute. If an attribute is not a mapping to the field of the database table, it must be marked as @ transient. Otherwise, the ORM framework defaults to its annotation as @ basic
  • @Temporal(TemporalType.DATE)
    This annotation can be used to adjust the accuracy of the database storage date during attribute mapping (by setting: TemporalType.DATE, TemporalType.TIMESTAMP)

6, JPQL and EntityManager

  • The simple entry code is as follows:

  • Entity: automatically generated by JPA

    package com.liu.susu.pojo;

    import javax.persistence.*;
    import java.util.Objects;

    @NamedQuery(name = "testNamedQuery",query = "select d from com.liu.susu.pojo.Dog d")
    @Entity
    public class Dog {
    private int dogNum;
    private String dogName;
    private String dogKind;
    private Integer dogAge;
    private String decision;

    public Dog(){
    
    }
    
    public Dog(int dogNum, String dogName) {
        this.dogNum = dogNum;
        this.dogName = dogName;
    }
    
    @Id
    @Column(name = "dog_num")
    public int getDogNum() {
        return dogNum;
    }
    
    public void setDogNum(int dogNum) {
        this.dogNum = dogNum;
    }
    
    @Basic
    @Column(name = "dog_name")
    public String getDogName() {
        return dogName;
    }
    
    public void setDogName(String dogName) {
        this.dogName = dogName;
    }
    
    @Basic
    @Column(name = "dog_kind")
    public String getDogKind() {
        return dogKind;
    }
    
    public void setDogKind(String dogKind) {
        this.dogKind = dogKind;
    }
    
    @Basic
    @Column(name = "dog_age")
    public Integer getDogAge() {
        return dogAge;
    }
    
    public void setDogAge(Integer dogAge) {
        this.dogAge = dogAge;
    }
    
    @Basic
    @Column(name = "decision")
    public String getDecision() {
        return decision;
    }
    
    public void setDecision(String decision) {
        this.decision = decision;
    }
    
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Dog dog = (Dog) o;
        return dogNum == dog.dogNum && Objects.equals(dogName, dog.dogName) && Objects.equals(dogKind, dog.dogKind) && Objects.equals(dogAge, dog.dogAge) && Objects.equals(decision, dog.decision);
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(dogNum, dogName, dogKind, dogAge, decision);
    }
    

    }

  • Two dao

    package com.liu.susu.dao;

    import com.liu.susu.pojo.Dog;
    import org.springframework.data.jpa.repository.JpaRepository;

    public interface DogDao extends JpaRepository<Dog,Integer> {

    }

    package com.liu.susu.dao;

    import com.liu.susu.pojo.Dog;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.data.jpa.repository.Query;

    import java.util.List;

    /**

    • jpql query
      /
      public interface DogDao2 extends JpaRepository<Dog,Integer> {
      /*

      • Check all without restrictions
      • @return
        */
        @Query(value = "from com.liu.susu.pojo.Dog")
        List getDogList();

      /**

      • Give an alias d, similar to query select*
      • @return
        */
        @Query(value = "select d from com.liu.susu.pojo.Dog d")
        List getDogList2();

      /**

      • In this way, the query result set of specific fields is not encapsulated in the entity object,
      •     It's encapsulated in Object[]in
        
      • @return
        */
        @Query(value = "select dogNum,dogName from com.liu.susu.pojo.Dog d")
        List<Object[]> getDogObjectList();

      /**

      • new, so the query result is directly encapsulated in the corresponding entity, but the corresponding constructor is required
      •      Therefore, if there are many fields to check, it will be more troublesome¬∑
        
      • @return
        */
        @Query(value = "select new com.liu.susu.pojo.Dog(dogNum,dogName) from com.liu.susu.pojo.Dog d")
        List getDogList3();

      /**

      • Query by criteria
      • @return
        */
        @Query(value = "select d from com.liu.susu.pojo.Dog d where d.dogAge=?1")
        List getDogList0(int dogAge);

    }

  • 4 controller s

    package com.liu.susu.controller;

    import com.alibaba.fastjson.JSONObject;
    import com.liu.susu.dao.DogDao;
    import com.liu.susu.pojo.Dog;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.domain.Sort;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;

    import java.util.List;

    @Controller
    @RequestMapping("/dog/dao1")
    public class DogDaoController {

    @Autowired
    private DogDao dogDao;
    
    /**
     * Query all
     * @return
     */
    @ResponseBody
    @RequestMapping("/all")
    public String testFindAll(){
        List<Dog> dogList = dogDao.findAll();
        return JSONObject.toJSONString(dogList);
    }
    /**
     * Query all and sort by dogAge field
     * @return
     */
    @ResponseBody
    @RequestMapping("/all2")
    public List<Dog> testFindAll2(){
    

    // List dogList = dogDao.findAll(Sort.by(“dogAge”));// Default ascending order
    List dogList = dogDao.findAll(Sort.by("dogAge").descending());
    return dogList;
    }
    /**
    *Query all and sort by dogAge field
    * @return
    */
    @ResponseBody
    @RequestMapping("/save")
    public List testSave(){
    Dog dog = new Dog();
    dog.setDogNum(1005);// Add primary key
    dog.setDogName("Su Ni");
    dog.setDogAge(1);
    dogDao.save(dog);// Save new
    List dogList = dogDao.findAll();
    return dogList;
    }

    }

    package com.liu.susu.controller;

    import com.liu.susu.dao.DogDao2;
    import com.liu.susu.pojo.Dog;
    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.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;

    import java.util.List;

    @Controller
    @RequestMapping("/dog/dao2")
    public class DogDao2Controller {
    @Autowired
    private DogDao2 dogDao2;

    @ResponseBody
    @RequestMapping("/list")
    private List<Dog> getDogList(){
        List<Dog> dogList = dogDao2.getDogList();
        return dogList;
    }
    @ResponseBody
    @RequestMapping("/list2")
    private List<Dog> getDogList2(){
        List<Dog> dogList = dogDao2.getDogList2();
        return dogList;
    }
    @ResponseBody
    @RequestMapping("/objList")
    private List<Object[]> getDogObjectList(){
        List<Object[]> dogObjectList = dogDao2.getDogObjectList();
        return dogObjectList;
    }
    @ResponseBody
    @RequestMapping("/list3")
    private List<Dog> getDogList3(){
        List<Dog> dogList = dogDao2.getDogList3();
        return dogList;
    }
    /**
     * Query by criteria
     * @param dogAge
     * @return
     */
    @ResponseBody
    @RequestMapping("/listByDogAge")
    private List<Dog> getDogListByParam(@RequestParam int dogAge){
        List<Dog> dogList = dogDao2.getDogList0(dogAge);
        return dogList;
    }
    

    }

    package com.liu.susu.controller;

    import com.liu.susu.pojo.Dog;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;

    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import javax.persistence.Query;
    import javax.transaction.Transactional;
    import java.util.List;

    @Controller
    @RequestMapping("/dog/entityManager1")
    public class EntityManagerController {

    @PersistenceContext
    private EntityManager entityManager;
    
    @ResponseBody
    @RequestMapping("/list1")
    public List<Dog> getDogList(){
        String sql = "select * from dog";
        List<Dog> dogList = entityManager.createNativeQuery(sql)
                .getResultList();//The result is only attribute value, not attribute name
        return dogList;
    }
    @ResponseBody
    @RequestMapping("/list2")
    public List<Dog> getDogList2(){
        String sql = "select * from dog";
        List<Dog> dogList = entityManager.createNativeQuery(sql,Dog.class)
                .getResultList();//Result = = > has attribute name
        return dogList;
    }
    /**
     * sql injection
     *    Query by parameters
     * @param dogNum
     * @return
     */
    @ResponseBody
    @RequestMapping("/dog1")
    public Dog getDogByNum(@RequestParam Integer dogNum){
        String sql = "select * from dog d where d.dog_num=?1";
        Query query = entityManager.createNativeQuery(sql,Dog.class);
        query.setParameter(1,dogNum);
        Dog dog = (Dog) query.getSingleResult();
        return dog;
    }
    @ResponseBody
    @RequestMapping("/save")
    @Transactional()//Remember to add transaction annotation
    public String testPersist(){
        Dog dog = new Dog();
        dog.setDogNum(1006);
        dog.setDogName("test");
        dog.setDogAge(0);
        entityManager.persist(dog);//Direct insert
        return "ok";
    }
    @ResponseBody
    @RequestMapping("/merge")
    @Transactional()//Remember to add transaction annotation
    public String testMerge(){
        Dog dog = new Dog();
        dog.setDogNum(1006);
        dog.setDogName("Test 2");
        dog.setDogAge(0);
        entityManager.merge(dog);//Internal principle: query according to the primary key first and then update
        return "ok";
    }
    

    }

    package com.liu.susu.controller;

    import com.liu.susu.pojo.Dog;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;

    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import java.util.List;

    @Controller
    @RequestMapping("/dog/jpqlAndEntityManager")
    public class JpqlAndEntityManagerController {

    @PersistenceContext
    private EntityManager entityManager;
    
    @ResponseBody
    @RequestMapping("/list1")
    public List<Dog> getDogList(){
        List<Dog> dogList = entityManager.createNamedQuery("testNamedQuery")
                .getResultList();
        return dogList;
    }
    

    }

7, Configuration file

  • to configure

    server.port=8993

    apply name

    spring.application.name=springboot-jpa

    Database driver:

    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

    Database connection address

    spring.datasource.url=jdbc:mysql://localhost:3306/liu?serverTimezone=UTC

    Database user name & password:

    spring.datasource.username=root
    spring.datasource.password=root

    #spring.jpa.generate-ddl=true
    #spring.jpa.hibernate.ddl-auto=validate
    spring.jpa.show-sql=true

    Specifies the type of database

    spring.jpa.database-platform=org.hibernate.dialect.MySQL57InnoDBDialect

  • pom

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


    4.0.0
    com.liu.susu
    springboot-jpa
    0.0.1-SNAPSHOT
    springboot-jpa
    Demo project for Spring Boot

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.2.RELEASE</spring-boot.version>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    
        <!--book demo Core dependency begin-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
    
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
    
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.14</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>
        <!--book demo Core dependency end-->
    
    </dependencies>
    
    
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>com.liu.susu.SpringbootJpaApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    

8, demo package

spring boot integrates JPA -- demo

Keywords: Java Front-end Spring Spring Boot html

Added by phpmoron on Sat, 05 Mar 2022 17:46:11 +0200