springboot basis jpa development 02

1. database operations

In spring boot in the operation of the database is easy, here we use jpa, jpa is to use Hibernate to generate a variety of automated sql, simple CRUD can achieve

1.1 add maven jpa dependent

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
 <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

1.2 class definition entities

package com.mp.prj;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "person_test")
public class Person implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    /**
     * 指定name,则为数据库中的列名,这里做个映射
     */
    @Column(name = "uname",length = 32,nullable = false,unique = true)
    private String name;
    /**
     * 省略默认列名就是属性名
     */
    @Column(length = 32)
    private String passwd;

    /*
    * @Transient 注解不会映射成表的字段 ,如果字段不写注解,则默认为@Column
    * */
    @Transient
    private String time;

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getPasswd() {
        return passwd;
    }

    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }

    public Person(String name,String passwd){
        this.name = name;
        this.passwd = passwd;
    }

    public Person(String name){
        this.name = name;
    }

    public Person(){}
}

Annotation Description:
(. 1) @Entity: is a mandatory annotation, the class declaration corresponds to a database table
(2) @Table (name = " person_test"): is an optional annotations, database tables and entity declarations mapping information, if not specified, the name of the entity on behalf of same table and
(3) @Id: declaration attribute uniquely identifies the entity corresponding to
(4) @GeneratedValue (strategy = GenerationType.IDENTITY ): growth from
(5) @Column (name = "uname", length = 32, nullable = false, unique = true): to the corresponding attribute declaration field, representing the field name specified entity inconsistent fields and tables, representing the same entity and the default field
(6) @Transient Notes field will not be mapped to the table, if the field is not written notes, the default is @Basic

Note: This must specify a default constructor

1.3 for persistence interface services

package com.mp.prj;


import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface PersonRepository extends JpaRepository<Person,Long> {
//    Person findbyName(String name);

    /*
    * 自定义查询, @Query 注解中增加一个 nativeQuery = true 的属性,就可以采用原生 SQL 语句的方式来编写查询
    * */
    @Query(nativeQuery = true, value = "select * from person_test where uname=:name and passwd = :passwd")
    List<Person> findPersonByNameAndPasswd(@Param("name") String name,@Param("passwd") String passwd);
}

Description Notes:
(1) @Repository: All marked @Repository classes will be registered as Bean the Spring
(2) By default, Jpa provides basic CRUD operations, are to meet the needs of
(3) where I also I wrote a method, in case we can not meet the needs of use, where the use of @Query annotations, you can customize sql query

1.4 realize Controller

package com.mp.prj;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/person")
public class PersonController {
    @Autowired
    PersonRepository personRepository;

    @RequestMapping("/insert")
    public String insertPerson(@RequestParam(value = "name") String name,
                            @RequestParam(value = "passwd") String passwd){
        personRepository.save(new Person(name,passwd));
        return "add person success";
    }

    @RequestMapping("/add/{name}")
    public String addPerson(@PathVariable("name") String name){
        personRepository.save(new Person(name));
        return "add person ok";
    }

    @RequestMapping("/findbyid/{id}")
    public Person findById(@PathVariable("id") String id){
        return personRepository.findById(Long.valueOf(id)).get();
    }

    @RequestMapping("/list")
    public List<Person> list(){
        return personRepository.findAll();
    }

    @RequestMapping("/find2/{name}/{passwd}")
    public List<Person> find2(@PathVariable("name") String name,
                        @PathVariable("passwd") String passwd){
        return personRepository.findPersonByNameAndPasswd(name,passwd);
    }
}

Annotation Description:
(. 1) @Autowired: by type (the byType) fitted dependent objects
(2) @PathVariable @RequestParam and
readily understood, again, no details

1.6 database configuration file

In the main path, the new resources folder designated as the Root Resources, New File application.yaml

spring:
  datasource:
    url: jdbc:mysql://10.1.0.9:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false
    username: test
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: update
      naming:
        physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy

    show-sql: true

ddl-auto Parameters:
(1) the Create: Every table is loaded once hibernate generated on will be deleted, and then re-generate a new table based on your model type, even if the two do not have any such change should be implemented, which It is an important cause of database tables of data loss.
(2) create-drop: loading each model class-table according to hibernate, but sessionFactory a closed table is automatically deleted.
(3) update: The most commonly used properties, when you first load hibernate automatically set up according to the model class structure of the table (the premise is to set up a good database), automatically updates the table structure based on model class is loaded hibernate later, even if the table structure change the rows in the table but does not delete the previous line still exists. Note that when deployed to the server, the table structure will not be immediately established, it is to wait after the first application up and running before.
(4) validate: every time you load hibernate, create a database table structure verification, and only tables in the database are compared, it does not create a new table, but will insert a new value.

1.7 Start Service

(1) New User: HTTP: // localhost:? 8080 / the Person / INSERT name = zhangsan1 & passwd = 123456
That success will insert a data into the database

(2) use PathVariable way new users:
HTTP: // localhost: 8080 / the Person / the Add / zhangsan2
(3) Find User:
HTTP: // localhost: 8080 / the Person / List
the other is no longer described in detail ...

1.8 Load Detailed Notes

After the topic for analysis

Guess you like

Origin blog.csdn.net/mapeng765441650/article/details/94716122