gpt4 book ai didi

java - Spring JPA插入连接表实体时不允许NULL

转载 作者:行者123 更新时间:2023-11-30 06:31:31 24 4
gpt4 key购买 nike

我有表结构

卖家

| 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;

}
<小时/>

当我尝试创建事务并使用 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 not allowed for column "CUSTOMER_ID"; SQL statement: insert into transaction (id) values (null) [23502-195]

当我调用save时,为什么不使用customer来填充CUSTOMER_ID

最佳答案

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

关于java - Spring JPA插入连接表实体时不允许NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46003562/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com