我有3个pojo:客户,产品和交易。
Customer.java :
@Id
@GeneratedValue
@Column
private Long id;
@Column
private String name;
// getters and setters
Product.java :
@Id
@GeneratedValue
@Column
private Long id;
@Column
private String productName;
// getters and setters
Transcation.java :
@Id
@GeneratedValue
@Column
private Long id;
@JoinColumn
@OneToOne // is this relation mapping correct
private Customer customer;
@JoinColumn
@OneToMany // is this relation mapping correct
private List<Product> product;
// getters and setters ... and my idea is one transcation multiple products for one customer at a time
我的 index.jsp 输入表单:
<form method="post" action="${pageContext.request.contextPath }/">
<div>
<label>User:</label>
<select name="customer">
<option value="">Select Customer</option>
<c:forEach var="c" items="${ cList }">
<option value="${ c.id }">${ c.name }</option>
</c:forEach>
</select>
</div><br>
<div>
<label>Hobby:</label>
<select name="product" multiple>
<!-- <option value="">Select Items</option> -->
<c:forEach var="p" items="${ pList }">
<option value = "${ p.id }">${ p.productName }</option>
</c:forEach>
</select>
</div>
<br><br>
<input type="submit" value="Send">
</form>
这是控制器:
@Controller
@RequestMapping(value = "/")
public class HomeController {
@Autowired
private CustomerDao customerDao;
@Autowired
private ProductDao productDao;
@Autowired
private TranscationDao transcationDao;
@RequestMapping(method = RequestMethod.GET)
public String home( Model model) {
model.addAttribute("cList", customerDao.getAllCustomer());
model.addAttribute("pList", productDao.getAllProduct());
return "index";
}
@RequestMapping(method = RequestMethod.POST)
public String postHome(Model model, @ModelAttribute Transcation t){
transcationDao.addTranscation(t);
return "home";
}
}
这是我的 TranscationDaoImpl :
@Override
public void addTranscation(Transcation t) {
session = sessionFactory.openSession();
session.save(t);
session.close();
}
我对如何将多个产品和客户数据插入数据库中的事务表感到困惑。
为了让我的交易功能在交易表中添加customer_id和多个product_id,我必须在代码中进行哪些修改。
在交易中,我有来自客户表的customer_id和来自产品表的product_id。
需要的是创建客户进行的每笔交易的数据库记录以及购买的产品清单。