Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a table of children each of which can have a set of different toys. There is a table that stores the code of each available toy.

@Entity
public class Child implements Serializable {
    @Id
    @GeneratedValue
    private int id;

    @OneToMany( mappedBy = "child", fetch = FetchType.EAGER, cascade = CascadeType.PERSIST )
    private Set<Toy> toys = new HashSet<>();

    // getters & setters
}

@Entity
public class ToyCode implements Serializable {
    @Id
    private int id;

    // getters & setters
}

@Entity
public class Toy implements Serializable {
    @EmbeddedId
    private ToyPK id = new ToyPK();

    @MapsId( "childId" )
    @ManyToOne
    private Child child;

    @MapsId( "toyId" )
    @ManyToOne  // <-- there is no cascade=CascadeType.PERSIST
    private ToyCode toyCode;

    // getters & setters
}

Although the toyCode member of Toy class has non cascading attribute Hibernate persists it.

Child elena = new Child();
Toy barbie = new Toy();
barbie.setChild( elena );
barbie.getId().setChildId( elena.getId() );
barbie.getId().setToyId( 4218 );
barbie.setToyCode( new ToyCode( 4218 ) );
elena.addToy( barbie );
em.persist(elena);

I've no 4218 record in ToyCode table but Hibernate creates it.

Am I wrong? Is this the right behavior or I should file a bug? If it is correct how can I prevent Hibernate to save new toy codes?

share|improve this question

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.