Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities

JPA(Java Persistence API) is an official Java Persistence specification proposed by Sun, mainly implemented by Hibernate, OpenJpA, etc. Spring Data JPA is a subproject of Spring Data that dramatically reduces the amount of code required for JPA as a Data access scheme by providing JPA-based Respositoty.

Create a table

CREATE TABLE `tb_user`  (
  `id` int(0) NOT NULL AUTO_INCREMENT COMMENT 'primary key',
  `user_name` varchar(32) NULL DEFAULT NULL COMMENT 'Username',
  `password` varchar(255) NULL DEFAULT NULL COMMENT 'password',
  `sex` varchar(2) NULL DEFAULT NULL COMMENT 'Sex 1- Male 2- Female 3- Unknown',
  `age` int NULL DEFAULT NULL COMMENT 'age',
  `email` varchar(64) NULL DEFAULT NULL COMMENT 'email',
  `create_time` datetime NULL DEFAULT NULL COMMENT 'Creation time',
  `update_time` datetime NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 'Update Time'.PRIMARY KEY (`id`) USING BTREE,
  INDEX `idx_username`(`user_name`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 0 COMMENT = 'User table' ROW_FORMAT = Dynamic;
Copy the code

Introduction of depend on

        <! --Spring data JPA-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <! --mysql connector-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
Copy the code

Adding a Configuration File

spring.datasource.url=jdbc:mysql://localhost:3306/miracle
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true
Copy the code

Add entity classes and DAOs

@Data
@Entity
@Table(name = "tb_user")
public class User {

    @Id
    @GeneratedValue
    private Integer id;
    @Column
    private String userName;
    @Column
    private String password;
    @Column
    private String sex;
    @Column
    private Integer age;
    @Column
    private String email;
    @Column
    private LocalDateTime createTime;
    @Column
    private LocalDateTime updateTime;
}

Copy the code
  • Entity: Each persistent POJO class is an Entity Bean, declared by using an Entity annotation in the class definition

  • Table: Declares this object to map the database data Table. This is not required; if not, the default value (the entity’s short class name) is used.

  • Id: Specifies the primary key of the table

We create a UserRepository interface class that inherits JpaRepository:

public interface UserRepository extends JpaRepository<User.Integer> {

    User findByUserName(String userName);

}
Copy the code

JpaRepository interface is a subclass of PagingAndSortingRepository and CrudRepository, CrudRepository class provides the basic add and delete etc interface, PagingAndSortingRepository class provides the basic paging and sorting interface, etc. In addition, we can also customize the query method. The findByUserName method above, for example, queries by user name. Spring Data JPA preorders a set of specifications for us, and as soon as we write code according to the specifications, Spring Data JPA will translate the code into relevant SQL statements for database queries. For example, you can use keywords Like findBy, Like, and In. FindBy can be read, readBy, Query, queryBy, get, and getBy instead. For more query methods, see the official documents.

Service Class implementation

public interface UserService {

    Optional<User> findById(int id);

    User findByUsername(String username);

    List<User> findAll(a);

    Page<User> findAll(Pageable pageable);
    
    void save(User user);
    
    void delete(User user);
}

@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserRepository userRepository;

    @Override
    public Optional<User> findById(int id) {
        return userRepository.findById(id);
    }

    @Override
    public User findByUsername(String username) {
        return userRepository.findByUserName(username);
    }

    @Override
    public List<User> findAll(a) {
        return userRepository.findAll();
    }

    @Override
    public Page<User> findAll(Pageable pageable) {
        return userRepository.findAll(pageable);
    }

    @Override
    public void save(User user) {
        userRepository.save(user);
    }

    @Override
    public void delete(User user) { userRepository.delete(user); }}Copy the code

We can write a Controller, here we use SpringBoot Test to Test.

test

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class UserServiceImplTest {

    @Autowired
    private UserService userService;

    @Test
    public void test(a) {
        User user = new User("miracle"."123456"."Male".20."[email protected]");
        User user1 = new User("miracle1"."123456"."Male".20."[email protected]");
        userService.save(user);
        userService.save(user1);
        List<User> users = userService.findAll();
        System.out.println(users);
        User miracle = userService.findByUsername("miracle");
        System.out.println(miracle);
        Pageable pageable = PageRequest.of(1.10); userService.findAll(pageable); userService.delete(user); }}Copy the code