introduce

  1. JPA is Spring Boot’s official recommended database access component.
  2. In contrast to MyBatis, Spring Data JPA uses entity objects to automatically create or modify database tables.

configuration

  1. ddl-autoIf configured ascreateorcreate-dropEach restart or sessionFactory shutdown deletes the previous table and creates it again, resulting in data loss.
  2. ddl-autoThe most commonly used attribute isupdateThat is, the table structure is updated with each restart.
  3. ddl-autoSet toupdateThere are a few details to note
    1. Although the name of the property isupdate, but only new operations are actually done, that is, deleting fields or modifying properties on entity objects does not synchronize database updates.
    2. If fields are added, they are added directly to the end of the database.
# application.yml
spring:
  jpa:
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    show-sql: true
    hibernate:
      ddl-auto: update # none validate update create create-drop
Copy the code

Entity objects

  1. Common notes and instructions
    1. @Table(name = "fh_user")
      1. Database table name
    2. @Column(name="user_name", length = 32)
      1. Name is the name of the database field. You are advised to specify all fields
      2. VarChar (32)
    3. @UpdateTimestamp
      1. Update time annotation, data update is the time this field will refresh
      2. The update mechanism is implemented by the framework, not the databaseON UPDATE CURRENT_TIMESTAMP
    4. @CreationTimestamp
      1. Create a time annotation that takes the current time when inserting data
      2. The update mechanism is implemented by the framework, not the databaseDEFAULT CURRENT_TIMESTAMP
@Getter
@Setter
@Entity
@Table(name = "fh_user")
public class UserDO {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    
    @Column(name="user_name", length = 32)
    private String userName;

    @Column(name="nike_name", length = 32)
    private String nikeName;

    @Column(name="sex")
    private Integer sex;

    @UpdateTimestamp
    @Column(name = "update_time")
    private Date updateTime;

    // Create time annotations
    @CreationTimestamp
    @Column(name = "create_time")
    private Date createTime;
}

Copy the code

Operational database (JpaRepository extension)

start

  1. In Spring Data JPA, databases are manipulated through Repository.
  2. The followingbeanOnce injected, it can be used directlyJpaRepositorySome common methods in interfaces
@Repository
public interface UserRepository extends JpaRepository<UserDO.Integer> {}Copy the code
@Resource
UserRepository userRepository;
Copy the code

new

UserDO user = new UserDO();
user.setSex(1);
user.setUserName("xxxx");
userRepository.save(user);
Copy the code

Modify the

Optional<UserDO> optional = userRepository.findFirstById(1); IfPresent ((user) -> {user.setusername ("aaaa"); userRepository.save(user); });Copy the code

delete

Optional<UserDO> option = userRepository.findById(1);

option.ifPresent((UserDO user) -> {
    userRepository.delete(user);
});
Copy the code

The query

Optional<UserDO> optional=userRepository.findById(1);
optional.ifPresent(user -> System.out.println(user.getUserName()));
Copy the code

Operating database (custom)

Custom method name query

Custom method name official document

Paging and sorting queries

Sort.TypedSort<UserDO> sort = Sort.sort(UserDO.class);
Slice<UserDO> users = userRepository.findByUserName("xxxx", PageRequest.of(0.10, sort.by(UserDO::getId).descending()));
Copy the code

The example query

UserDO userDO = new UserDO();
userDO.setSex(1);
Example<UserDO> example = Example.of(userDO);
List<UserDO> users = userRepository.findAll(example);
Copy the code