如何在不为每个事务保存父项的情况下保存子实体

时间:2016-03-21 23:35:41

标签: spring jpa transactions

我正在使用Spring Data JPA存储库。我有一个卡实体和一个交易实体。当用户使用卡进行交易时,我想保存卡和交易(购买/退款)实体。但是当用户执行下一个事务时,我只想保存Transaction实体。我的实体是:

Card Entity

@Entity
@Table(name = "CARD")
public class Card {


    @Id
    private Long card_id;

    public Long getCard_id() {
        return card_id;
    }

    public void setCard_id(Long card_id) {
        this.card_id = card_id;
    }


    private String type;

}

Transaction Entity

@Entity
@Table(name="Transaction")
public class Transaction {

    @Id
    @SequenceGenerator( name="TRAN_SEQ1", initialValue=5,sequenceName="TRAN_SEQ1", allocationSize=1 )
    @GeneratedValue( strategy=GenerationType.SEQUENCE, generator="TRAN_SEQ1")
    private long id;

    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name = "card_id")
    private Card card;

    public Card getCard() {
        return card;
    }

    public void setCard(Card card) {
        this.card = card;
    }

}

我尝试了以下方法,但在保存时抛出异常:

Transaction t = new Transaction();
Card c = cardRepository.getOne(123L);
t.setCard(c);
transactionRepository.save(t);
**Exception :       
org.hibernate.PersistentObjectException: uninitialized proxy passed to persist()**

我不确定我错过了什么。任何人都可以在这里指导我..

1 个答案:

答案 0 :(得分:0)

您是否尝试添加反向关系?

import numpy as np
tmp = np.random.rand(5,1)
lol = lambda first, second: float(first)/second
print tmp
np.apply_along_axis(lol, 1, tmp, second=1) #works but I don't want this
np.apply_along_axis(lol, 1, tmp, first=1)  # doesn't work