设计数据库的一些坑的总结。
1.Int与Integer的区别
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
@Entity @Table(name = "tb_student") @Cache(usage=CacheConcurrencyStrategy.READ_WRITE) public class Student {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; private String name; private int age; private int gender; }
|
2.有依赖关联表与无依赖关联表
一张表里只能有一个主键,或者有一种情况是one primary key included two fileds.
有依赖关联表:通过在用户信息表里加入用户ID实现两张表的关联。
具体实现:
逻辑模型
物理模型
无依赖关联表:通过引入第三张表来进行用户表与用户信息表的关联。
3.Hibernate中一对一、一对多以及多对多的注解实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
@Entity @Table(name = "tb_person") public class Person {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id;
private String name;
private int age;
@OneToOne(mappedBy="person") private IdCard card; }
@Entity @Table(name = "tb_idcard") public class IdCard {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String sno;
@OneToOne @JoinColumn(name="person_id", unique=true) private Person person; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
@Entity @Table(name = "tb_dept") @Cache(usage=CacheConcurrencyStrategy.READ_WRITE) public class Department {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(length = 50) private String name;
private int sn;
@OneToMany(mappedBy = "dept") private Set<Employee> emps = new HashSet<Employee>(); }
@Entity @Table(name="tb_emp") @Cache(usage=CacheConcurrencyStrategy.READ_WRITE) public class Employee {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; private String name; @ManyToOne @JoinColumn(name="dept_id") private Department dept; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
@Entity @Table(name = "tb_course") public class Course {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name;
@ManyToMany @JoinTable(name="tb_student_course", joinColumns=@JoinColumn(name="course_id"), inverseJoinColumns=@JoinColumn(name="student_id")) private Set<Student> students = new HashSet<Student>(); }
@Entity @Table(name="tb_student") public class Student {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; private String name; @ManyToMany(mappedBy="students") private Set<Course> courses = new HashSet<Course>(); }
|