Hiberante(七) Annotation的方式实现ManyToOne,OneToOne,ManyTOMany

 Annotation实现ManyToOne

    实体类:

   CassRoom.java

@Entity //注解成一个实体类
@Table(name="t_classroom") //对应数据库中表
public class ClassRoom {
    private int id;
    private String name;
    private int grade;
    
    @Id  //主键
    @GeneratedValue //主键生成方式-->自增长
    public int getId() {
	return id;
    }

 省略其他get,set(不配置其他属性对应的数据库中属性,就是以默认值)
}

 Student.java

@Entity
@Table(name = "t_student")
public class Student {

	private int id;
	private String name;
	private String no;
	private ClassRoom classroom;

	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}

     	@ManyToOne(fetch = FetchType.LAZY)// fetch=FetchType.LAZY 延迟加载
	@JoinColumn(name = "cid")//外键
	public ClassRoom getClassroom() {
		return classroom;
	}
  省略其他get,set
}

Annotation 实现OneToOne

  实体类:

  Person.java

@Entity
@Table(name="t_person")
public class Person {
     
	private int id;
	private String name;
	private IDCard idcard;
	
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}

        @OneToOne
	@JoinColumn(name="cid")
	public IDCard getIdcard() {
		return idcard;
	}
   省略其他get,set
}

  IDCarid.java

@Entity
@Table(name="t_idcard")
public class IDCard {
   
	private int id;
	private String no;
	private Person person;
	
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	@OneToOne(mappedBy="idcard")//当双向关联时,设置下由谁维护关系
	public Person getPerson() {
		return person;
	}
  省略其他get,set
}

Annotation 实现ManyToMany

  实体类

  Teacher.java

@Entity
@Table(name="t_teacher")
public class Teacher {
	private int id;
	private String name;
	private Set<TeacherCourse> tcs;
	
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	@OneToMany(mappedBy="teacher")
	@LazyCollection(LazyCollectionOption.EXTRA)
	public Set<TeacherCourse> getTcs() {
		return tcs;
	}

  Course.java

@Entity
@Table(name="t_course")
public class Course {
	private int id;
	private String name;
	private Set<TeacherCourse> tcs;
	
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	@OneToMany(mappedBy="course")
	@LazyCollection(LazyCollectionOption.EXTRA)
	public Set<TeacherCourse> getTcs() {
		return tcs;
	}

TeacherCourse.java

@Entity
@Table(name="t_teacher_course")
public class TeacherCourse {
	private int id;
	private double ach;
	private Teacher teacher;
	private Course course;
	
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	@ManyToOne
	@JoinColumn(name="tid")
	public Teacher getTeacher() {
		return teacher;
	}
		
	@ManyToOne
	@JoinColumn(name="cid")
	public Course getCourse() {
		return course;
	}

相关推荐