注解配置一对一

Hibernate一对一外键双向关联(Annotation配置)
如上图所示:一个学生有一个学生证号,一个学生证号对应一名学生。在Hibernate中怎么用Annotation来实现呢?
学生类,主键是id;学生证的主键也是Id;
Student.java
package edu.xaut.hibernate;

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

@Entity
public class Student {
 
   private intid;
    privateString name;
    privateString gender;
    private intage;
    privateStuIdCard stuIdCard;

    @Id
   @GeneratedValue
    public intgetId() {
       returnid;
    }

    @Column(name= "name", length = 20)
    publicString getName() {
       returnname;
   }   

    @Column(name= "gender", length = 6)
    publicString getGender() {
       returngender;
    }

    public intgetAge() {
       returnage;
    }

   @OneToOne
   @JoinColumn(name = "StuIdCard")
    publicStuIdCard getStuIdCard() {
       returnstuIdCard;
    }

    public voidsetId(int id) {
       this.id =id;
    }

    public voidsetName(String name) {
       this.name =name;
    }
   
    public voidsetGender(String gender) {
       this.gender= gender;
    }
   
    public voidsetAge(int age) {
       this.age =age;
    }

    public voidsetStuIdCard(StuIdCard stuIdCard) {
      this.stuIdCard = stuIdCard;
    }
}

package edu.xaut.hibernate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;

@Entity
public class StuIdCard {
    private intid;
    privateString num;
    privateStudent student;

    @Id
   @GeneratedValue
    public intgetId() {
       returnid;
    }

    public voidsetId(int id) {
       this.id =id;
    }

   @Column(length = 20)
    publicString getNum() {
       returnnum;
    }

    public voidsetNum(String num) {
       this.num =num;
    }

   @OneToOne(mappedBy="stuIdCard")
    publicStudent getStudent() {
       returnstudent;
    }

    public voidsetStudent(Student student) {
       this.student= student;
  
阅读更多
个人分类: java
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭