Hibernate学习笔记_09_单向联合组建外键关联关系

情境描述:学生与成绩之间是单向关系,成绩由课程编号和开课学期来决定。

1、首先编写联合主键类。

package com.hibernate._0900_oneToone_uni_fk_composite; import java.util.Date; public class ScorePK implements java.io.Serializable{ private String courseID; private Date data; //开课学期 public String getCourseID() { return courseID; } public void setCourseID(String courseID) { this.courseID = courseID; } public Date getData() { return data; } public void setData(Date data) { this.data = data; } }
联合主键类必须实现Serializable接口。


2、编写成绩类。

package com.hibernate._0900_oneToone_uni_fk_composite;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;

@Entity
@IdClass(ScorePK.class)
public class Score {
	private String courseID;
	private Date data;    //开课学期
	private String courseName;
	
	@Id
	public String getCourseID() {
		return courseID;
	}
	public void setCourseID(String courseID) {
		this.courseID = courseID;
	}
	@Id
	public Date getData() {
		return data;
	}
	public void setData(Date data) {
		this.data = data;
	}
	public String getCourseName() {
		return courseName;
	}
	public void setCourseName(String courseName) {
		this.courseName = courseName;
	}	
}
设置@IdClass来指定联合主键类,并将作为联合主键的属性都注解为@Id。这个类中的联合主键属性应该和作为联合主键类中的属性名称和类型一致。

3、编写学生类。

package com.hibernate._0900_oneToone_uni_fk_composite;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.OneToOne;

@Entity
public class Student {
	private Integer id;
	private String name;
	private Score score;	 

	@Id
	@GeneratedValue
	public Integer getId() {
		return id;
	}
	public String getName() {
		return name;
	}
	@OneToOne    //设置关联关系
	@JoinColumns(   {
		@JoinColumn(name="c_id",referencedColumnName="courseID"),
		@JoinColumn(name="c_name",referencedColumnName="courseName")
		}
	   )
	public Score getScore() {
		return score;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setScore(Score score) {
		this.score = score;
	}
}
设置关联关系,可以用@JoinColumns注解来修改属性在数据库中对应的字段名称。@JoinColumns接受的参数是一个JoinColumn类型的数组,联合主键时,需要用referencedColumnName来指定哪个字段名对应类中的哪个属性




你可能感兴趣的:(Date,数据库,Hibernate,String,Integer,Class)