简体   繁体   English

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

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

I started to learn hibernate JPA and I try to create bidirectional one-to-many relation, but for some reason it results with org.hibernate.exception.ConstraintViolationException: could not execute statement我开始学习 hibernate JPA 并尝试创建双向一对多关系,但由于某种原因,它会导致org.hibernate.exception.ConstraintViolationException: could not execute statement

Let's say I have an entity Card and entity Deck.假设我有一个实体卡和实体甲板。 And each Deck can have multiple cards, but every card can belong only to single deck.每副牌可以有多张牌,但每张牌只能属于一副牌。 I made it this way:我是这样做的:

This is the card entity:这是卡实体:

/**
 * 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;
}

And this is the deck:这是甲板:

/**
 * 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<>();
}

Now this is my repository where I want to persist the card entity:现在这是我要保存卡实体的存储库:

    ...
    /**
     * @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;
        }
    }
    ...

While executing entityManager.flush() it crashes because of violated constraint.在执行entityManager.flush()时,由于违反约束而崩溃。 I can't just imagine why.我无法想象为什么。

Because the Deck that is referenced by Card#deck is unmanaged and/or the id it has does not exist.因为Card#deck引用的Deck是非托管的和/或它具有的 id 不存在。 If you want to save the Deck along with the card, you need to configure PERSIST cascading on Card#deck .如果要将Deck与卡一起保存,则需要在Card#deck上配置 PERSIST 级联。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM