【问题标题】:Hibernate JPA bidirectional one-to-many results with constraint violation exceptionHibernate JPA双向一对多结果与约束冲突异常
【发布时间】: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


    【解决方案1】:

    因为Card#deck 引用的Deck 是非托管的,并且/或者它的id 不存在。如果要将Deck与卡一起保存,则需要在Card#deck上配置PERSIST级联。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-08
      • 2019-04-13
      • 2012-08-10
      • 1970-01-01
      • 2015-06-22
      • 1970-01-01
      • 2017-11-05
      • 1970-01-01
      相关资源
      最近更新 更多