07, operation of the database by springdata jpa

Us on one of springboot build a simple application, which will introduce the use of a spring-data-jpa operation of the database.

Create a new MySQL database, where the database called springboot, establish user_info data table, as the table object example of our operations.

user_info information is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

DROP TABLE IF EXISTS `user_info`;

CREATE TABLE `user_info` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `username` varchar(255) DEFAULT NULL,

  `passwordvarchar(255) DEFAULT NULL,

  PRIMARY KEY (`id`)

) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

 

-- ----------------------------

-- Records of user_info

-- ----------------------------

INSERT INTO `user_info` VALUES ('1''Java之音''12345');

INSERT INTO `user_info` VALUES ('2''张无忌''123');

  

After a successful database and table creation, back to our project

Step Zero, first introduced in MySQL and jpa maven dependencies:

1

2

3

4

5

6

7

8

9

<dependency>

      <groupId>mysql</groupId>

      <artifactId>mysql-connector-java</artifactId>

 </dependency>

 

 <dependency>

       <groupId>org.springframework.boot</groupId>

       <artifactId>spring-boot-starter-data-jpa</artifactId>

 </dependency>

  

The first step, configure the database connection information in the yml configuration file:

1

2

3

4

5

6

7

8

spring:

  datasource:

    driver-class-name: com.mysql.jdbc.Driver

    url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useSSL=false

    username: root

    password: 1011

  jpa:

    show-sql: true

  

Next, create an entity class, the corresponding data entity mapping table:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

package com.javazhiyin;

 

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

 

/**

* Created by 57783 on 2018/7/4.

*/

@Entity

public class UserInfo {

 

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Integer id;

 

    private String username;

 

    private String password;

 

    public Integer getId() {

        return id;

    }

 

    public void setId(Integer id) {

        this.id = id;

    }

 

    public String getUsername() {

        return username;

    }

 

    public void setUsername(String username) {

        this.username = username;

    }

 

    public String getPassword() {

        return password;

    }

 

    public void setPassword(String password) {

        this.password = password;

    }

 

    public UserInfo(){

 

    }

}

  

The third step is to create a Repository class that inherits JpaRepository categories:

1

2

3

4

5

6

7

8

9

10

package com.javazhiyin;

 

import org.springframework.data.jpa.repository.JpaRepository;

 

/**

* Created by 57783 on 2018/7/4.

*/

public interface UserInfoRepository extends JpaRepository<UserInfo,Integer>{

 

}

  

Here inherited JpaRepository class that encapsulates some of the basic method of database operations, we look through the source code JpaRepository What are some ways:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

//

// Source code recreated from a .class file by IntelliJ IDEA

// (powered by Fernflower decompiler)

//

 

package org.springframework.data.repository;

 

import java.util.Optional;

 

@NoRepositoryBean

public interface CrudRepository<T, ID> extends Repository<T, ID> {

    <S extends T> S save(S var1);

 

    <S extends T> Iterable<S> saveAll(Iterable<S> var1);

 

    Optional<T> findById(ID var1);

 

    boolean existsById(ID var1);

 

    Iterable<T> findAll();

 

    Iterable<T> findAllById(Iterable<ID> var1);

 

    long count();

 

    void deleteById(ID var1);

 

    void delete(T var1);

 

    void deleteAll(Iterable<? extends T> var1);

 

    void deleteAll();

}

  

The fourth step, a new Controller, additions and deletions to achieve the change to the database search operation:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

package com.javazhiyin;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

 

import java.util.List;

 

/**

* Created by 57783 on 2018/7/4.

*/

@RestController

public class UserInfoController {

 

    @Autowired

    private UserInfoRepository userInfoRepository;

 

    /**

     * 查

     * @return

     */

    @GetMapping(value = "/list")

    public List<UserInfo> getUserList(){

        return userInfoRepository.findAll();

    }

 

    /**

     * 增

     * @param username

     * @param password

     * @return

     */

    @PostMapping(value = "/addUser")

    public UserInfo addUser(@RequestParam("username") String username,

                            @RequestParam("password") String password){

        UserInfo user = new UserInfo();

        user.setUsername(username);

        user.setPassword(password);

        return userInfoRepository.save(user);

    }

 

    /**

     * 改

     * @param id

     * @param username

     * @param password

     * @return

     */

    @PutMapping(value = "updUser/{id}")

    public UserInfo updUser(@PathVariable("id") Integer id,

                        @RequestParam("username") String username,

                        @RequestParam("password") String password){

        UserInfo user = new UserInfo();

        user.setId(id);

        user.setUsername(username);

        user.setPassword(password);

        return userInfoRepository.save(user);

 

    }

 

    /**

     * 删

     * @param id

     */

    @DeleteMapping(value = "delUser/{id}")

    public void delUser(@PathVariable("id") Integer id){

        UserInfo user = new UserInfo();

        user.setId(id);

        userInfoRepository.delete(user);

    }

 

}

  

Test the code above, here we use postman test is very easy:

Query test:

New test:

 

Modify the test:

 

Delete the test:

 

We can see through all the tests, springboot using spring-data-jpa CRUD operations were indeed very convenient.

 

a few questions:

 

1, annotation objects @GeneratedValue entity mapping class concept and usage?

 

JPA requires each entity Entity, you must have one and only one primary key, and @GeneratedValue annotations to generate the primary key is a unique identifier of an entity.

JPA provides four primary key generation strategy is defined in an enumeration class GenerationType, respectively:

  1. GenerationType.TABLE
  2. GenerationType.SEQUENCE
  3. GenerationType.IDENTITY
  4. GenerationType.AUTO

 

GenerationType.TABLE

使用一个特定的数据库表格来保存主键,持久化引擎通过关系数据库的一张特定的表格来生成主键。这种策略的好处是不依赖于外部环境和数据库的具体实现,在不同数据库间可以很容易的进行移植。但由于其不能充分利用数据库的特性,所以不会优先使用。

 

GenerationType.SEQUENCE

在某些数据库中不支持主键自增长,比如Oracle。其提供了一种叫做”序列(sequence)”的机制生成主键。此时,GenerationType.SEQUENCE就可以作为主键生成策略。该策略的不足之处正好与TABLE相反,由于只有部分数据库(Oracle,PostgreSQL,DB2)支持序列对象,所以该策略一般不应用于其他数据库。

 

GenerationType.IDENTITY

主键自增长策略,数据库在插入数据时,会自动给主键赋值,比如MYSQL可以在创建表时声明”auto_increment” 来指定主键自增长。该策略在大部分数据库中都提供了支持(指定方法或关键字可能不同),但还是有少数数据库不支持,所以可移植性略差。

 

GenerationType.AUTO

把主键生成策略交给持久化引擎(persistence engine),持久化引擎会根据数据库在以上三种主键生成策略中选择其中一种。此种主键生成策略比较常用,由于JPA默认的生成策略就是GenerationType.AUTO,所以使用此种策略时可以显式的指定@GeneratedValue(strategy = GenerationType.AUTO)也可以直接@GeneratedValue。

 

2、Spring Data JPA提供了哪些接口,可以实现哪些功能?

 

  1. Repository:最顶层的接口,是一个空的接口,目的是为了统一所有Repository的类型,且能让组件扫描的时候自动识别。
  2. CrudRepository :是Repository的子接口,提供CRUD的功能
  3. PagingAndSortingRepository:是CrudRepository的子接口,添加分页和排序的功能
  4. JpaRepository:是PagingAndSortingRepository的子接口,增加了一些实用的功能,比如:批量操作等。
  5. JpaSpecificationExecutor:用来做负责查询的接口
  6. Specification:是Spring Data JPA提供的一个查询规范,要做复杂的查询,只需围绕这个规范来设置查询条件即可

 

原文;https://www.cnblogs.com/javazhiyin/p/9297743.html

发布了740 篇原创文章 · 获赞 65 · 访问量 10万+

Guess you like

Origin blog.csdn.net/qq_41723615/article/details/104282177