【发布时间】:2020-12-28 17:39:23
【问题描述】:
我开始学习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() 时,由于违反约束而崩溃。我无法想象为什么。
【问题讨论】:
标签: java spring hibernate jpa h2