springDataJpa的demo

1. 添加jpa相关的maven依赖(一般创建springboot项目是勾选好)

 

 

2. 配置jpa和jdbc的配置信息(application.yml)

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root
    url: jdbc:mysql://127.0.0.1:3306/demo?useSSL=false&characterEncoding=utf-8&serverTimezone=UTC
  jpa:
    hibernate:
      ddl-auto: update
    database-platform: org.hibernate.dialect.MySQLDialect
    show-sql: true

 

 

3. 数据库创建对应的表,并用idea连接数据库

 

 

 

 

 

4.创建对应的实体类

  @Data省略get/set、toString方法

  @Entity表明该类作为实体类

    @Entity(name = 'student' )  表明该类对应于数据库中的student表,在实体类名字和表明不一致的时候使用

  @Table(name = 'student') 表明该类对应于数据库中的student表,在实体类名字和表明不一致的时候使用

    该注解其他属性catalog 和 schema

  @Id表明该属性为表中的主键

  另外还有两个注解@GeneratedValue、@GenericGenerator

@Data
@Entity
@Table(name = "student")
public class Student {
    @Id
    private Long id;
    private String name;
    private Integer age;
}

 

 

5. 创建dao类,并提供对应的方法

public interface TestDao extends JpaRepository<Student, Integer> {}

 

 

  该类继承自JpaRepository类,默认提供以下方法(即继承而来的方法)(不全)

  

  

  自定义查询方法(即sql语句)有以下两种原则

    ①基于方法名称

    List<Student> findByName(String name);      //指定姓名查找
    List<Student>  findByAgeGreaterThanEqual(int age);      //大于指定年龄查找;

 

    ②基于@Query注解(注意sql语句的写法)

    @Query(value = "select s from Student s where age > ?1")
    List<Student> findByAge(int age);

 

 

排序查询:

        List<Student> age = testDao.findAll(Sort.by("age"));
        System.out.println(age);

 

posted @ 2021-02-02 14:43  气球i  阅读(210)  评论(0编辑  收藏  举报