当前位置: 代码迷 >> Web前端 >> Hibernate基础之8:一对一单/双向,主/外键关联 @OneToOne@JoinColumn
  详细解决方案

Hibernate基础之8:一对一单/双向,主/外键关联 @OneToOne@JoinColumn

热度:346   发布时间:2012-11-21 08:23:26.0
Hibernate基础之八:一对一单/双向,主/外键关联 @OneToOne@JoinColumn


1:一对一,单向,外键关联

Student和stusentIDCard两张表是一对一的关系,即一个学生只有一个学生证,一个学生证只对应一个学生

Stuent表里有个外键要参考StudentIDCard

表现类上就是Student实例里聚合一个stusentIDCard

@Entity
public class Student 
{
	private int id;
	private String name;
	private int age;
	private StudentIDCard cardId;
	
	@Id
	@GeneratedValue//可以定单独的自增序列,这共用一个
	public int getId() {
		return id;
	}
	@OneToOne//一对一的关系
	@JoinColumn(name="card_Id")//指定外键名称是card_Id
	public StudentIDCard getCardId() {
		return cardId;
	}


@Entity
public class StudentIDCard 
{
	private int id;
	private String kinds;
	private Date datePublished;
	
	@Id
	@GeneratedValue//可以定义单独的自增序列,这里共用一个
	public int getId() {
		return id;
	}

测试类

	@Test
	public void testIN() {	
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        StudentIDCard sic = new StudentIDCard();
        sic.setKinds("primarySchool");
        sic.setDatePublished(new Date());
        session.save(sic);
        
		Student s = new Student();
		s.setName("李四");
		s.setAge(0);
		s.setCardId(sic);
        session.save(s);

        session.getTransaction().commit();
        HibernateUtil.getSessionFactory().close();         
	}
	@Test
	public void testShow() {
		new SchemaExport(new AnnotationConfiguration().configure()).create(false,true);
	}


建表结果:

foreign key (card_Id) references StudentIDCard

16:15:13,184 DEBUG SchemaUpdate:226 - create table Student (id number(10,0) not null, age number(10,0) not null, name varchar2(255 char), card_Id number(10,0),primary key (id))
16:15:13,193 DEBUG SchemaUpdate:226 - create table StudentIDCard (id number(10,0) not null, datePublished timestamp, kinds varchar2(255 char), primary key (id))
16:15:13,200 DEBUG SchemaUpdate:226 - alter table Student add constraint FKF3371A1BEA113360foreign key (card_Id)references StudentIDCard


PowerDesigner里反向工程出来的图如下:


就是Student表里的字段要去参考StudenIDCard表里的东西,外键名字我指定的是:“CARD_ID”







2:一对一,双向,外键关联

双向表现在类上就是:Student和stusentIDCard互相聚合一个实例,

双方都标注@OneToOne


Student类不变,参考上边那个,不赘述了

@Entity
public class StudentIDCard 
{
	private int id;
	private String kinds;
	private Date datePublished;
	private Student student;
	
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	@OneToOne//互相持有,都加了OneToOne
	public Student getStudent() {
		return student;
	}

但这样就等于会在表里出现重复的字段,还要设置mappedBy,说明对方是主导,消除冗余
StudentIDCard类的getStudent()上
@OneToOne(mappedBy="StudentIDCard")说明对方是主导,对方(Student)的"cardId"属性已经做映射了,消除互相是外键的冗余
getStudent()

	@OneToOne(mappedBy="cardId")//说明对方是主导,对方(Student)的"cardId"属性已经做映射了,消除互相是外键的冗余
	public Student getStudent() {
		return student;
	}




3:一对一,单向,主键关联

@JoinColumn换成@PrimaryKeyJoinColumn//指定外键名字

@JoinColumn换成@PrimaryKeyJoinColumn//指定外键名字

















  相关解决方案