Hibernate many-to-one - bad usage?
Posted
by DaveA
on Stack Overflow
See other posts from Stack Overflow
or by DaveA
Published on 2010-04-05T20:33:47Z
Indexed on
2010/04/05
20:43 UTC
Read the original article
Hit count: 195
hibernate
Just trying out Hibernate (with Annotations) and I'm having problems with my mappings. I have two entity classes, AudioCD and Artist.
@Entity
public class AudioCD implements CatalogItem {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String title;
@ManyToOne(cascade = { CascadeType.ALL }, optional = false)
private Artist artist;
....
}
@Entity
@Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "name" }) })
public class Artist {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(nullable = false)
private String name;
.....
}
I get AudioCD objects from an external source. When I try to persist the AudioCD the Artist gets persisted as well, just like I want to happen. If I try persisting another different CD, but Artist already exists I get errors due to constraint violations.
I want Hibernate to recognise that the Artist already exists and shouldn't be inserted again. Can this be done via annotations? Or do I have to manage the persistence of the AudioCD and Artist seperately?
© Stack Overflow or respective owner