插入连接表实体时不允许使用Spring JPA NULL

时间:2017-09-01 15:29:36

标签: java spring hibernate jpa

我有表结构

卖方

  

| ID |

客户

  

| ID |

交易

  

| ID | SELLER_ID | CUSTOMER_ID |

我代表这些实体:

@Entity
@Table(name = "SELLER")
public class Seller {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    @OneToMany(mappedBy = "seller", fetch = FetchType.LAZY, orphanRemoval = true)
    private List<Transaction> transactions;

}
@Entity
@Table(name = "CUSTOMER")
public class Customer {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    @OneToMany(mappedBy = "customer", fetch = FetchType.LAZY, orphanRemoval = true)
    private List<Transaction> transactions;
}
@Entity
@Table(name = "TRANSACTION")
public class Transaction {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(
            name = "SELLER_ID",
            insertable = false,
            updatable = false,
            nullable = false,
            foreignKey = @ForeignKey(name = "TRA_SLR_FK")
    )
    private Seller seller;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(
            name = "CUSTOMER_ID",
            insertable = false,
            updatable = false,
            nullable = false,
            foreignKey = @ForeignKey(name = "TRA_CMR_FK")
    )
    private Customer customer;

}

当我尝试创建一个Transaction并使用CrudRepository保存它时:

public interface TransactionRepository extends CrudRepository<Transaction,Long> {}

使用:

Customer customer = customerRepository.findOne(1L); // Similar CrudRepository    
Seller seller = sellerRepository.findOne(1L); // Similar CrudRepository    
Transaction transaction = new Transaction(seller, customer);
transaction = transactionRepository.save(transaction);

我收到错误:

  

列不允许NULL&#34; CUSTOMER_ID&#34 ;; SQL语句:插入   transaction(id)values(null)[23502-195]

为什么我拨打customer时没有使用CUSTOMER_ID填充save

1 个答案:

答案 0 :(得分:1)

根据doc,可插入,可更新等属性是指SQL生成,而不是插入或更新相关实体。