java - Prevent duplicate entry for unique constraint -
i trying save tags related article in mysql database. relation between 2 columns 1:n. each item has auto generated key. name of tag unique.
if insert new article existing tag, duplicate entry exception unique constraint (mysqlintegrityconstraintviolationexception). 2 entities:
article.java
@entity public class article implements serializable { @id @generatedvalue(strategy = generationtype.identity) private long id; @onetomany(cascade = cascadetype.all) @jointable private set<tag> tags = new hashset<tag>(); /* getter , setter */ }
tag.java
@entity public class tag implements serializable { @id @generatedvalue(strategy = generationtype.identity) private long id; @column(unique = true) private string name; /* getter , setter */ }
hibernate generate following tables: article, tag, article_tag. first article records correct.
i use following code insert new article (only testing):
article article = new article(); tag tag = new tag(); /* set values */ entitymanager em = emf.getinstance().get(); em.gettransaction().begin(); em.merge(article); em.gettransaction().commit();
how jpa use existing tag article instead of create new one. how set relation between components correctly?
in general relationship between articles , tags many-to-many relationship article may have many tags , each of these tags may reused in many articles.
to indicate many-to-many relationship @manytomany annotation required.
also make clear, in op indicated unidirectionaly one-to-many relationship @jointable annotation has been used on many side. reason join table has been created. in addition consequence if @manytoone annotation used in tag
class many-to-one unidirectional relationship. just careful there handled 2 independent unidirectional relationship probable strange behaviour , configuration not affect both entities, since not biderictional relationship.
finally, if required have one-to-many unidirectional relationship reuse tags, required retrieve them based on name, have correct record id , set article
instance. if try set new instance of tag
have no record id name exists, jpa provider try insert new tag , unique constraint exception thrown, because of duplicate tag name. need remove unique constraint referred tag_id
in article_tag
table.
Comments
Post a Comment