简体   繁体   中英

Hibernate persists referenced entities without cascade=PERSIST

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?

It's the intended behavior. When you map an entity with @MapsId you get the cascade PERSIST too. It seems logic to me as the @MapsId("toyId") needs to point to a an existing entity with that primary key value.

See this JIRA issue: https://hibernate.atlassian.net/browse/HHH-4858

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM