[英]Hibernate JPA bidirectional one-to-many results with constraint violation exception
我開始學習 hibernate JPA 並嘗試創建雙向一對多關系,但由於某種原因,它會導致org.hibernate.exception.ConstraintViolationException: could not execute statement
假設我有一個實體卡和實體甲板。 每副牌可以有多張牌,但每張牌只能屬於一副牌。 我是這樣做的:
這是卡實體:
/**
* Represents a card in deck.
*
* @author wintermute
*/
@Data
@Entity(name = "card")
@Table(name = "card")
@NamedQueries( {@NamedQuery(name = "Card.getAll", query = "SELECT c FROM card c WHERE c.containedInDeck = :deck_id"),
@NamedQuery(name = "Card.remove", query = "DELETE FROM card c WHERE c.id = :id")})
public class Card
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String containedText;
@ManyToOne
@JoinColumn(name = "deck_id")
private Deck containedInDeck;
}
這是甲板:
/**
* Represents card deck containing cards sorted by deck's type.
*
* @author wintermute
*/
@Data
@Entity
@Table(name = "deck")
public class Deck
{
@Id
@GeneratedValue
private long id;
@Column(name = "type")
private String typeOfDeck;
@OneToMany(mappedBy = "containedInDeck")
@ElementCollection(targetClass = Card.class)
private Set<Card> containedCards = new HashSet<>();
}
現在這是我要保存卡實體的存儲庫:
...
/**
* @param card to persist in database.
* @return true if operation was successful, false if operation failed.
*/
public long add(Card card)
{
try
{
entityManager.getTransaction().begin();
entityManager.persist(card);
entityManager.flush();
entityManager.getTransaction().commit();
return card.getId();
} catch (IllegalStateException | PersistenceException e)
{
log.error("Could not save entity: " + card + ", message: " + e.getMessage());
return -1L;
}
}
...
在執行entityManager.flush()
時,由於違反約束而崩潰。 我無法想象為什么。
因為Card#deck
引用的Deck
是非托管的和/或它具有的 id 不存在。 如果要將Deck
與卡一起保存,則需要在Card#deck
上配置 PERSIST 級聯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.