Hibernate many-to-one - bad usage?
- by DaveA
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?