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?
No, AFAIK you can't.
Since name
is unique for every Artist
instance, you should try to lookup an artist by name (via session.createCriteria(Artist.class).add(Restrictions.eq("name", artistName)).uniqueResult()
or get yourself some service class with method Artist findByName(String artistName)
) and then decide, whether to persist an artist or to use existing one.
精彩评论