# Re:0 - Starting Life in Backend - Day2

seal

我好想你
在每个夜里
孤单自叙
纷飞的回忆
猜不透你
褪色的熟悉
是我编造的幻觉


Level 4: Data Storage - Integrating H2 Database with JPA

Target: Set user's data into H2 database , and perform simple add, delete, modify and query operations through JPA

Solution:

Redefine models

@Entity     //@Entity annotation indicates that this class is a JPA entity,which will be mapped to a table in the database
public class UserH2 {

    @Id      
    // @Id annotation indicates that this field is the primary key of the entity
    @GeneratedValue(strategy = GenerationType.IDENTITY)         
    // @GeneratedValue indicates that the primary key value is automatically generated.Here use the IDENTITY strategy ,the database automatically increments.
    
    private Long id;    // as primary key value

    @JsonProperty("username")
    private String username;
    @JsonProperty("age")
    private int age;

    // No-argument constructor
    public UserH2(){
    }

    // Constructor with parameters
    public UserH2(String username, int age) { 
        this.username = username;
        this.age = age;
    }

    {The same}

}

Compared to the code before , the code snippet above add some new annotations to fit H2 and JPA

Create Repository

public interface UserH2Repository extends JpaRepository<UserH2, Long> {
    //username
    UserH2 findByUsername(String username);
    List<UserH2> findByUsernameContainingIgnoreCase(String keyword);//containing;IgnoreCase
    List<UserH2> findByUsernameStartingWith(String keyword);
    List<UserH2> findByUsernameEndingWith(String keyword);
    List<UserH2> findByUsernameIsNull();
    List<UserH2> findByUsernameIsNotNull();
    List<UserH2> findByUsernameLikeIgnoreCase(String keyword);  
    //here when using ,you need to add '%' in front and back of the keyword

    //age
    List<UserH2> findByAge(int age);
    List<UserH2> findByAgeGreaterThan(int age);
    List<UserH2> findByAgeBetween(int age1, int age2);
    List<UserH2> findByAgeIn(List<Integer> age);
    List<UserH2> findByAgeOrderByUsernameDesc(int age);
    List<UserH2> findTop3ByAge(int age);

}

JPA provides a unique and efficient way to define specific names to implement different SQL data processing functions.

Such as findTop3ByUsernameLikeIgnoreCase above, can be divided into

  1. find Indicates a search operation
  2. Top3 Indicates the quantity to search
  3. Username Indicates the key to search
  4. Like Indicates the query operation
  5. IgnoreCase Indicates the query modification operations

Use Repository in the Controller

@RestController
@RequestMapping("/userH2")
public class UserH2Controller {
    // here use userH2Repository to connect H2 database 
    private final UserH2Repository userH2Repository;

    public UserH2Controller(UserH2Repository userH2Repository) {
        this.userH2Repository = userH2Repository;
    }

    @PostMapping
    public UserH2 save(@RequestBody UserH2 userH2) {
        return userH2Repository.save(userH2);
    }

    @GetMapping("/getAll")
    public List<UserH2> findAll() {
        return userH2Repository.findAll();
    }

    @GetMapping("/getByUsername")
    public UserH2 findByUsername(
            @RequestParam(name = "username", required = true ) String username
            ) {
        return userH2Repository.findByUsername(username);
    }

    @GetMapping("/getByUsernameLike")
    public List<UserH2> findByUsernameLikeIgnoreCase(
            @RequestParam(name = "key", required =true ) String username
            ) {
        return userH2Repository.findByUsernameLikeIgnoreCase("%"+username+"%");
    }
}

Here use @RequestMapping("/userH2") indicate that All /userH2 routes will be directed to this class

And we use the userH2Repository to connect H2 database .


Test

We can use POSTlocalhost:port/userH2 to save data

@PostMapping
public UserH2 save(@RequestBody UserH2 userH2) {
return userH2Repository.save(userH2);
}

Then use GETlocalhost:port/userH2/getAll to get all of the datas

@GetMapping("/getAll")
public List findAll() {
return userH2Repository.findAll();
}

use GETlocalhost:port/userH2/getByUsername?username=seal can search specific username in the H2 database

@GetMapping("/getByUsername")
public UserH2 findByUsername(
@RequestParam(name = "username", required = true ) String username
) {
return userH2Repository.findByUsername(username);
}

and use GETloaclhost:port/userH2/getByUsernameLike?username=seal

@GetMapping("/getByUsernameLike")
public List findByUsernameLikeIgnoreCase(
@RequestParam(name = "key", required =true ) String username
) {
return userH2Repository.findByUsernameLikeIgnoreCase("%"+username+"%");
}


Level 4-s

the solution above use some new dependences——H2 & JPA , but we have already created this project, how do we add new dependencies?

Here we need to use a external plugin——EditStarters

after downloading , we can just **right click in the pom.xml file, then click "Generate/",and click "Edit starters" **