我在db中有两个带有ff列的模型:
ContractHeader
id = primary key
con_num
ContractEntitlement
id = primary key
ch_id = foreign key to id in ContractHeader table
category
一个合约标题可以有多个合约权利。模型类是:
ContractHeader.java
@Entity
@Table(name = "CONTRACT_HEADER")
public class ContractHeader {
@Id
@Column(name = "id", unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "contractHeader")
private List<ContractEntitlement> contractEntitlements;
@Column(name = "con_num")
private String conNum;
getter and setter ....
ContractEntitlement
@Entity
@Table(name = "CONTRACT_ENTITLEMENT")
public class ContractEntitlement {
@Id
@Column(name = "id", unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ch_id", referencedColumnName = "id")
private ContractHeader contractHeader;
@Column(name = "category")
private String category;
getter and setter ....
当我从jsp保存日期时,它正确地在spring中插入每个表没有错误的值,但是ch_id字段(foreign_key)总是为空。知道为什么ch_is没有被来自contractheader表的id填充?
答案 0 :(得分:1)
这不是问题的答案,而是更多的解决方法,并希望分享。而不是在db方面处理我在保存后会话关闭之前得到id:
public String addContractHeader(@Validated @ModelAttribute("contractHeader") ContractHeader p, BindingResult bindingResult, Model model) {
System.out.println("BEFORE " + p.getId());
this.contractHeaderService.addContractHeader(p);
System.out.println("AFTER " + p.getId());
for (Iterator<ContractEntitlement> i = p.getContractEntitlements().iterator(); i.hasNext();) {
ContractEntitlement employee = i.next();
-- use p.getId() to store in ch_id (foreign_key)
this.contractEntitlementService.addContractEntitlement(employee);
}
BEFORE 0
Hibernate: insert into CONTRACT_HEADER (contact_email, contact_number, contact_person, contract_number, contract_package, contract_status, contract_sum, contract_type, currency_type, customer_address, customer_name, expiry_date, package_other, remarks, start_date) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Info: INFO : com.at.ccts.dao.ContractHeaderDAOImpl - ContractHeader saved successfully, ContractHeader Details=com.at.ccts.model.ContractHeader@39d1a603
2017-05-01T20:01:52.537+0800|Info:
AFTER 19
我将id存储在db(序列化)中。