我有一個登記表:如何使用hibernate使用具有關係映射的表單將值插入到多個表中?
<form action="${ pageContext.request.contextPath }/customer/add" method="post">
<div>
<label>Name: </label>
<input type="text" name="name">
</div>
<div>
<label>Address: </label>
<input type="text" name="address.address">
</div>
<input type="submit" value="Insert">
在這裏,我想插入此表的值轉換成客戶和地址帳戶具有以下POJO:
Cusotmer.java
@Id
@GeneratedValue
@Column
private Long id;
@Column
private String name;
@OneToOne
@JoinColumn(name = "address_id")
private Address address;
Address.java
@Id
@GeneratedValue
@Column
private Long id;
@Column
private String address;
我創建了一個daoImpl方法來增加客戶和它們各自的地址:
CustomerDaoImpl
@Override
@Transactional
public void addCustomer(Customer c) {
session = sessionFactory.openSession();
session.beginTransaction();
session.save(c);
session.getTransaction().commit();
session.close();
}
AddressDaoImpl
@Override
@Transactional
public void addAddress(Address a) {
session = sessionFactory.openSession();
session.beginTransaction();
session.save(a);
session.getTransaction().commit();
session.close();
}
CustomerController
@Autowired
private CustomerDao customerDao;
@Autowired
private AddressDao addressDao;
@RequestMapping(value="/customer/add", method = RequestMethod.POST)
public String postCustomer(@ModelAttribute Customer c, @ModelAttribute Address a){
addressDao.addAddress(a);
c.setAddress(a);
customerDao.addCustomer(c);
return "redirect:/customer";
}
插入操作不工作的唯一地址值。客戶與相應的address_id一起被添加,但是在地址表本身中,地址名稱不會被插入,只是id被創建。
*不工作*表示?任何錯誤消息? – Jens
客戶與address_id一起添加,但在地址表中創建地址,但不保存表單值。 @Jens – Space
在前端使用db實體並不是一個好主意。你應該使用pojo,它只存儲普通數據。一個實體在後臺有很多對象 – Jens