Hibernate JPA 双向一对多结果与约束违反异常

Hibernate JPA bidirectional one-to-many results with constraint violation exception

我开始学习 hibernate JPA 并尝试创建双向一对多关系,但由于某种原因,结果为 org.hibernate.exception.ConstraintViolationException: could not execute statement

假设我有实体卡片和实体卡片组。每个Deck可以有多张牌,但每张牌只能属于一个牌组。我是这样做的:

这是卡片实体:

/**
 * 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 是非托管的 and/or 它的 ID 不存在。如果要将Deck连同卡一起保存,需要在Card#deck.

上配置PERSIST级联