2012-12-08 202 views
3

我有一個對一類學生和班級點之間Hibernate映射:Hibernate的一個一對一的映射

@Entity 
@Table(name = "Users") 
public class Student implements IUser { 

    @Id 
    @Column(name = "id") 
    private int id; 

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

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

    @OneToOne(fetch = FetchType.EAGER, mappedBy = "student") 
    private Points points; 

    @Column(name = "type") 
    private int type = getType(); 
    //gets and sets... 



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

    @GenericGenerator(name = "generator", strategy = "foreign", parameters = @Parameter(name = "property", value = "student")) 
    @Id 
    @GeneratedValue(generator = "generator") 
    @Column(name = "id", unique = true, nullable = false) 
    private int Id; 


    @OneToOne 
    @PrimaryKeyJoinColumn 
    private Student student; 
    //gets and sets 

然後我做的:

Student student = new Student(); 
     student.setId(1); 
     student.setName("Andrew"); 
     student.setPassword("Password"); 

     Points points = new Points(); 
     points.setPoints(0.99); 

     student.setPoints(points); 
     points.setStudent(student); 

     Session session = HibernateUtil.getSessionFactory().getCurrentSession(); 
     session.beginTransaction(); 
     session.save(student); 
     session.getTransaction().commit(); 

和Hibernate可以節省學生表格但不保存相應的點。可以嗎?我應該分別保存點嗎?

+0

我認爲你需要保存'Pointer'也 –

回答

2
@OneToOne(fetch = FetchType.EAGER, mappedBy = "student", cascade=CascadeType.PERSIST) 
private Points points; 

你可以試試這個。

+0

感謝它幫助Points :) –

2

默認情況下,沒有操作在Hibernate中級聯。您應該在您的一對一關係中指定CascadeType。

1

如果你想保存Student,你需要使用CascadeType在你的註釋,在這裏看到documentation