3

我在班级学生和班级点之间有一对一的休眠映射:

@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将student保存在表中,但不保存对应的点。可以吗?我应该单独保存积分吗?

4

3 回答 3

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

你能试试这个。

于 2012-12-08T16:53:01.757 回答
2

默认情况下,Hibernate 中没有级联操作。您应该在一对一关系中指定 CascadeType。

于 2012-12-08T16:53:49.670 回答
1

如果您想保存StudentPoints您需要CascadeType在注释中使用,请参阅此处获取文档

于 2012-12-08T16:55:38.233 回答