JPA全称是Java Persistence Api,作用类似于MyBatis,是ORM(对象关系映射)。

JPA的查询语言是面向对象的,而不是面向数据库的

开启JPA的使用

首先,要想在Java中使用JPA,则先在maven中引入JPA的依赖

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

然后,实体类跟数据库对应,Patient为实体类。@Table注解中的patient为数据库表,表示Patient类与数据库表patient对应。@Column中的字段为patient表中字段,和类中的字段一一对应。

@Entity
@Table(name = "patient")
public class Patient {
    @Id
    private Integer patientId;
    @Column(name = "document_type")
    private String documentType;
    @Column(name = "document_number")
    private Integer documentNumber;
    @Column(name = "english_surname")
    private String englishSurname;
    public Patient(String documentType) {
    this.documentType = documentType;
}

最后,写JPA查询语句,首先得建一个类,该类继承JpaRepository<ClassName,Type>接口,该接口的第一个参数为实体类,第二个参数为实体类的@Id修饰的字段类型。然后就能在该类中,写查询语句了。

JPA有自己的一套查询语句:通过解析方法名来解析查询语句,一般的格式为findBy字段名,如果限定条件有多个字段,则为findBy字段名And字段名。还能在service层进行默认查询,比如save(),findAll()方法

 public interface PatientRepository extends JpaRepository<Patient,Integer> {

    /**
     * jpa自己的一套查询方法
     */
    List<Patient> findByPatientId(Integer num); 
    List<Patient> findByPatientIdAndMobilePhone(Integer num, String str); 
    List<Patient> findByMobilePhone(Integer num);
    List<Patient> findByEnglishSurname(String str);



    /**
     * 如果要自己书写查询语句,则需要加上@Modifying和@Query(),@Query里书写语句 
     * 如果为更新语句,一般加上事务,即@Transactional注解
     */
    @Transactional(rollbackFor = Exception.class) 
    @Modifying
    @Query("update Patient p set p.documentType = ?2, p.documentNumber = ?3, p.englishSurname = ?4 where p.patientId = ?1")
    int updateById(Integer patientId, String documentType, Integer documentNumber, String englishSurname);

    /**
     * 该为自己手写 select, 如果查询出返回的结果只是documentType,则在实体类中
     * 一定要添加该字段的构造函数
     */       
    @Query("select new com.harmonycloud.entity.Patient(p.documentType) from Patient p where p. patientId = ?1")
    List<String> findByPatientId(Integer patientId);

    /**
     * 模糊查询 在模糊查询的字段后面加上Containing。建议使用Containing,
     * 不要使用like
     */
    // 对appointmentDate进行模糊查询
    List<Appointment> findByAppointmentDateContaining(String appointmentDate);

    //对roomId进行精确查询,对appointmentDate进行模糊查询
    List<Appointment> findByRoomIdAndAppointmentDateContaining(Integer roomId, String appointmentDate);


    /**
     * 在网上找到模糊查询的方法都是如下这种,但是这种在我这都不行,我也找不出原因,
     * 所有我就使用了Containing关键字方法,要是like使用不了,建议使用Containing
     */
    @Query("select new com.harmonycloud.entity.Appointment(a.appointmentId, a.patientId, a.clinicId, a.encounterTypeId," +
        "a.roomId, a.appointmentDate, a.status, a.attendanceStatus, a.attendanceTime) from Appointment a where appointmentDate = '?1%'")
List<Appointment> findByAppointmentDateContaining(String appointmentDate);

}