出道题给大家玩玩
public class Customer {
private Long id;
private String name;
private Set<Linkman> linkmans = new HashSet<Linkman>(0); // 一对多
}
public class Linkman implements java.io.Serializable{
private Long id;
private String name;
private Customer customer; // 多对一
}
package test.java;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import util.HibernateUtils;
import entity.Customer;
import entity.Linkman;
/**
* 请说明以下语句各显示发送多少条SQL语句,是否报错,外键是否保存
* 并说明在Customer设置不维护外键inverse="true"的情况下的结果
*/
public class SaveTest {
@Test
public void saveTest() throws Exception {
// 1.多对一先存多:
saveCommand("lc", "sl", "sc");
// 2.多对一先存一:
saveCommand("lc", "sc", "sl");
// 3.一对多先存多:
saveCommand("cl", "sl", "sc");
// 4.一对多先存一:
saveCommand("cl", "sc", "sl");
// 5.互关联先存多:
saveCommand("cl", "lc", "sl", "sc");
// 6.互关联先存一:
saveCommand("cl", "lc", "sc", "sl");
// 7.多对一只存多:
saveCommand("lc", "sl");
// 8.多对一只存一:
saveCommand("lc", "sc");
// 9.一对多只存多:
saveCommand("cl", "sl");
// 10.一对多只存一:
saveCommand("cl", "sc");
// 11.互关联只存多:
saveCommand("cl", "lc", "sl");
// 12.互关联只存一:
saveCommand("cl", "lc", "sc");
}
public void saveCommand(String... commands) {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
Customer customer = new Customer();
customer.setName("客户");
Linkman linkman1 = new Linkman();
linkman1.setName("联系人1");
Linkman linkman2 = new Linkman();
linkman2.setName("联系人2");
for (String command : commands) {
switch (command) {
case "lc": // 多对一
linkman1.setCustomer(customer);
break;
case "cl": // 一对多
customer.getLinkmans().add(linkman1);
break;
case "sc": // 存一
session.save(customer);
break;
case "sl": // 存多
session.save(linkman1);
break;
default:
break;
}
System.out.println(" " + customer + "\n " + linkman1);
}
System.out.println("提交:");
tx.commit();
System.out.println(" " + customer + "\n " + linkman1);
}
}