SpringBoot整合JPA和Hibernate框架

Springboot整合JPA+Hibernate框架【待完成】

  • 随着MybatisPlus技术的发展,JPA和Hibernate技术已经逐步淘汰
    JPA遵循了Hibernate框架规则,目前使用的不多
1、添加依赖

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-data-jpaartifactId>
dependency>
2、添加配置
# JPA配置
spring.jpa.database = MYSQL
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
3、创建单表实体
  • @Entity
  • @Table
@Data
@Entity
@Table(name = "student")
public class Student implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id ;
    private String name;
    private Byte sex;
    private String numberId;
}
@Data
@Entity
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "student_id")
    private int id;
    
    @Column(name = "student_name")
    private String name;
    
    @Column(name = "student_password")
    private String password;
    //多对一字段
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "school")
    private School school;
    //多对多字段
    @ManyToMany(cascade = CascadeType.ALL,mappedBy = "students")//mappedBy=“关联属性名”
    private Set<Teacher> teachers;
}
@Data
@Entity
@Table(name = "teacher")
public class Teacher {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "teacher_id")
    private int id;
    @Column(name = "teacher_name")
    private String name;
    @Column(name = "teacher_password")
    private String password;
    
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "school")
    private School school;
    
    @ManyToMany(cascade = CascadeType.ALL)
        @JoinTable(name = "teacher_student",//中间表名
        joinColumns = {@JoinColumn(name = "teacherid")},//当前对象id在中间表的列名
        inverseJoinColumns = {@JoinColumn(name = "studentid")}//另一张表在中间表的列名
    )
    private Set<Student> students;

}

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class School {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "school_id")
    private int id;
    @Column(name = "school_name")
    private String name;
    @OneToMany(cascade = CascadeType.ALL,mappedBy = "school")
    private Set<Student> students;
    @OneToMany(cascade = CascadeType.ALL,mappedBy = "school")
    private Set<Teacher> teachers;
}

你可能感兴趣的:(spring,boot,hibernate,java)