如何在一对一映射中连接非主键列并根据该列选择记录

时间:2016-12-02 05:38:38

标签: hibernate

我已检查过以下编码是否适用于一对一关系,但问题是它为已放置的已连接非主键列refID

所需的主键值

我没有得到答案

Data should save like this image

家长班

@Entity
@Table(name = "Parent")
public class Parent {

    @Id
    @GenericGenerator(name = "j", strategy = "increment")
    @GeneratedValue(generator = "j")

    @Column(name = "parentId")
    private Long parentId;

    @Column(name = "parentName")
    private String parentName;

    @Column(name = "prentEmail")
    private String prentEmail;

    @Column(name = "cell_phone")
    private String cellphone;

    @Column(name = "refID")
    private String refID;

    @OneToOne(mappedBy = "parent", cascade = CascadeType.ALL)
    private Student student;

    public Parent() {

    }

    public Parent( String parentName, String prentEmail, String cellphone, String refID) {


        this.parentName = parentName;
        this.prentEmail = prentEmail;
        this.cellphone = cellphone;
        this.refID = refID;

    }
// getters and setters
}

学生班

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

    @Id
    @Column(name="studentID", unique=true, nullable=false)
    @GeneratedValue(generator="gen")
    @GenericGenerator(name="gen", strategy="foreign", parameters=@Parameter(name="property", value="parent"))


    private Long studentId;

    @Column(name = "studentName")
    private String studentName;

    @Column(name = "studentEmail")
    private String studentEmail;

    @Column(name = "StudentCLassName")
    private String StudentCLassName;

    @OneToOne
    @PrimaryKeyJoinColumn
    private Parent parent;

    public Student() {

    }

    public Student( String studentName, String studentEmail, String studentCLassName) {

        this.studentName = studentName;
        this.studentEmail = studentEmail;
        StudentCLassName = studentCLassName;

    }
// gettters and setters
}

MainClass

public class HibernateTest {
    public static void main(String[] args) {

        Parent parent=new Parent("Eregowda","Er@gmail.com","9964289813","ReferenceID1");
        Student student=new Student("Pradee","p@gmail.com","10th");

        Configuration cfg = new Configuration();
        cfg.configure();

        SessionFactory factory = cfg.buildSessionFactory();
        Session session = factory.openSession();

        Transaction tx = session.beginTransaction();
        tx.begin();



        parent.setStudent(student);
        student.setParent(parent);


        session.save(parent);

        tx.commit();
        session.close();


    }
}

2 个答案:

答案 0 :(得分:0)

您必须通过指定特定列在学生班中使用@JoinColumn来加入列。

@OneToOne(optional = true)
@JoinColumn(name = "parent", referencedColumnName = "refID", insertable = false, updatable = false)

答案 1 :(得分:-1)

var top = event.target.offsetTop + 'px';