I have a JPA object like this:
@Entity
@Table(name = "category")
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@Column(name = "name")
private String name;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "category")
private Collection<ItemCategory> itemCategoryCollection;
}
Use Mysql as a Base Database. "name" is a unique key. Use Hibernate as a JPA Provider.
The problem with using the merge method is that since pk is generated by db, so if the record already exists (the name already exists), Hibernate will try to insert it into db, and I will get a unique key constraint exception exception and without updating. Does anyone have a good practice to handle this? Thank!
PS: my workaround is as follows:
public void save(Category entity) {
Category existingEntity = this.find(entity.getName());
if (existingEntity == null) {
em.persist(entity);
} else {
entity.setId(existingEntity.getId());
em.merge(entity);
}
}
public Category find(String categoryName) {
try {
return (Category) getEm().createNamedQuery("Category.findByName").
setParameter("name", categoryName).getSingleResult();
} catch (NoResultException e) {
return null;
}
}
source
share