spring data jpa 使用(mysql)

1. 包依赖

compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('mysql:mysql-connector-java:8.0.12')

2. 使用@EnableJpaAuditing

@SpringBootApplication
@EnableJpaAuditing
public class LblApplication {

3. properties配置

spring.datasource.url=jdbc:mysql://localhost:3306/lbl?useSSL=false&characterEncoding=utf-8
spring.datasource.username=lbl
spring.datasource.password=lbl
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql=true

4. 实体

@Entity //声明为实体
@EntityListeners(AuditingEntityListener.class) //使CreatedDate/LastModifiedDate注解生效
public class Music{
    @Id //声明为ID
    @GeneratedValue(strategy= GenerationType.IDENTITY) //mysql 自增ID
    Long id;
    @CreatedDate // 自动填充创建时间
    Date createdTime;
    @LastModifiedDate  // 自动填充更新时间
    Date updatedTime;
}

5. 实现JpaRepository接口

public interface MusicRepository extends JpaRepository<Music, Long> {

6. 常用方法

//有则更新,无则添加
musicRepository.save(music);
//music空的字段会被忽略,非空的字段就作为where条件,根据createdTime降序排列
musicRepository.findAll(Example.of(music), new Sort(Direction.DESC,"createdTime"));
//删除时需先find该对象,再delete

你可能感兴趣的:(jpa)