我正在尝试在Java中有效地实现Hibernate连接,最近遇到了两种使用Hibernate添加数据库行的方法,我想讨论一下:
给出以下SQL表:
CREATE TABLE Customer (
customer_id INT NOT NULL AUTO_INCREMENT,
customer_name VARCHAR(255) NOT NULL UNIQUE KEY,
PRIMARY KEY (customer_id)
) ENGINE=InnoDB;
CREATE TABLE Orders (
order_id INT NOT NULL AUTO_INCREMENT,
customer_name VARCHAR(255) NOT NULL,
order_date DATETIME,
PRIMARY KEY(order_id),
FOREIGN KEY (customer_name) REFERENCES Customer(customer_name)
ON UPDATE CASCADE
ON DELETE CASCADE
) ENGINE=InnoDB;
客户是父表,订单是子表,1:n关系。
当我想为已经在数据库中的某个客户插入新订单时,我知道选项如何实现它:
(1)
// Saving the child table
// Query the customer
Customer cu = (Customer) session.get(Customer.class, 1);
Orders od = new Orders(cu, new Date());
session.save(od);
// This seems to work fast and efficient
(2) Saving the parent table
// Due to bidirectional relationship one can also do:
Orders od = new Orders(cu, d);
cu.getOrderses().add(od);
session.save(cu);
// This is what is often shown in Hibernate tutorials, but seems to be really
// inefficient because the entire HashSet of the parent table needs to loaded //first,
//before the new object can be added.
基准示例:(1)0秒(2)5秒
为什么方式(2)经常在教程中显示,即使它似乎效率低下?
答案 0 :(得分:1)
您应该在模型上选择哪个选项。您是否需要在客户中收集订单?然后你必须添加对象,你应该选择(2)。
注意正确的获取配置,否则即使您不需要,Hibernate也会加载整个集合。对于这种情况,请查看Hibernate - How to persist a new item in a Collection without loading the entire Collection。
如果您在Customer中没有集合,请使用选项(1)。
(2)经常在教程中显示,以显示Hibernate / ORM的一般功能。它也更面向对象,但我建议创建一个方法Customer.addOrder()
甚至Customer.creatOrder()
,而不是直接从外部操纵集合。