Andrey Yaskulsky
Andrey Yaskulsky

Reputation: 2516

Hibernate one-to-one mapping

I have one-to-one hibernate mapping between class Student and class Points:

@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

And then i do:

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();

And hibernate saves student in the table but not saves corresponding points. Is it OK? Should i save points separately?

Upvotes: 3

Views: 1148

Answers (3)

Atropo
Atropo

Reputation: 12531

If you want to save the Student and the Points you need to use the CascadeType in your annotation, see here for documentation

Upvotes: 1

Art Licis
Art Licis

Reputation: 3679

By default, no operations are cascaded in Hibernate. You should specify CascadeType on your one-to-one relationship.

Upvotes: 2

Subin Sebastian
Subin Sebastian

Reputation: 10997

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

Can you try this.

Upvotes: 2

Related Questions