1. 一对多和多对一关系
1.1 模型分析
Snip20180810_37.png
1.2 建表
- 创建Customer表
CREATE TABLE `t_customer` (
`cust_id` BIGINT(32) NOT NULL AUTO_INCREMENT COMMENT '客户编号(主键)',
`cust_name` VARCHAR(32) NOT NULL COMMENT '客户名称(公司名称)',
`cust_source` VARCHAR(32) DEFAULT NULL COMMENT '客户信息来源',
`cust_industry` VARCHAR(32) DEFAULT NULL COMMENT '客户所属行业',
`cust_level` VARCHAR(32) DEFAULT NULL COMMENT '客户级别',
`cust_linkman` VARCHAR(64) DEFAULT NULL COMMENT '联系人',
`cust_phone` VARCHAR(64) DEFAULT NULL COMMENT '固定电话',
`cust_mobile` VARCHAR(16) DEFAULT NULL COMMENT '移动电话',
PRIMARY KEY (`cust_id`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
- 创建LinkMan表
CREATE TABLE `cst_linkman` (
`lkm_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '联系人编号(主键)',
`lkm_name` varchar(16) DEFAULT NULL COMMENT '联系人姓名',
`lkm_cust_id` bigint(32) NOT NULL COMMENT '客户id',
`lkm_gender` char(1) DEFAULT NULL COMMENT '联系人性别',
`lkm_phone` varchar(16) DEFAULT NULL COMMENT '联系人办公电话',
`lkm_mobile` varchar(16) DEFAULT NULL COMMENT '联系人手机',
`lkm_email` varchar(64) DEFAULT NULL COMMENT '联系人邮箱',
`lkm_qq` varchar(16) DEFAULT NULL COMMENT '联系人qq',
`lkm_position` varchar(16) DEFAULT NULL COMMENT '联系人职位',
`lkm_memo` varchar(512) DEFAULT NULL COMMENT '联系人备注',
PRIMARY KEY (`lkm_id`),
KEY `FK_cst_linkman_lkm_cust_id` (`lkm_cust_id`),
CONSTRAINT `FK_cst_linkman_lkm_cust_id` FOREIGN KEY (`lkm_cust_id`) REFERENCES `t_customer` (`cust_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
1.3 创建与表对应的实体类,描述两者间的关系
- 创建Customer类
public class Customer {
private Long cust_id;
private String cust_name;
private String cust_source;
private String cust_industry;
private String cust_level;
private String cust_linkman;
private String cust_phone;
private String cust_mobile;
// 使用set集合表达一对多关系
private Set linkMen = new HashSet();
public Set getLinkMen() {
return linkMen;
}
public void setLinkMen(Set linkMen) {
this.linkMen = linkMen;
}
public Long getCust_id() {
return cust_id;
}
public void setCust_id(Long cust_id) {
this.cust_id = cust_id;
}
public String getCust_name() {
return cust_name;
}
public void setCust_name(String cust_name) {
this.cust_name = cust_name;
}
public String getCust_source() {
return cust_source;
}
public void setCust_source(String cust_source) {
this.cust_source = cust_source;
}
public String getCust_industry() {
return cust_industry;
}
public void setCust_industry(String cust_industry) {
this.cust_industry = cust_industry;
}
public String getCust_level() {
return cust_level;
}
public void setCust_level(String cust_level) {
this.cust_level = cust_level;
}
public String getCust_linkman() {
return cust_linkman;
}
public void setCust_linkman(String cust_linkman) {
this.cust_linkman = cust_linkman;
}
public String getCust_phone() {
return cust_phone;
}
public void setCust_phone(String cust_phone) {
this.cust_phone = cust_phone;
}
public String getCust_mobile() {
return cust_mobile;
}
public void setCust_mobile(String cust_mobile) {
this.cust_mobile = cust_mobile;
}
@Override
public String toString() {
return "Customer [cust_id=" + cust_id + ", cust_name=" + cust_name + "]";
}
- 创建LinkMan类
public class LinkMan {
private Long lkm_id;
private Character lkm_gender;
private String lkm_name;
private String lkm_phone;
private String lkm_email;
private String lkm_qq;
private String lkm_mobile;
private String lkm_memo;
private String lkm_position;
//表达多对一关系
private Customer customer ;
public Long getLkm_id() {
return lkm_id;
}
public void setLkm_id(Long lkm_id) {
this.lkm_id = lkm_id;
}
public Character getLkm_gender() {
return lkm_gender;
}
public void setLkm_gender(Character lkm_gender) {
this.lkm_gender = lkm_gender;
}
public String getLkm_name() {
return lkm_name;
}
public void setLkm_name(String lkm_name) {
this.lkm_name = lkm_name;
}
public String getLkm_phone() {
return lkm_phone;
}
public void setLkm_phone(String lkm_phone) {
this.lkm_phone = lkm_phone;
}
public String getLkm_email() {
return lkm_email;
}
public void setLkm_email(String lkm_email) {
this.lkm_email = lkm_email;
}
public String getLkm_qq() {
return lkm_qq;
}
public void setLkm_qq(String lkm_qq) {
this.lkm_qq = lkm_qq;
}
public String getLkm_mobile() {
return lkm_mobile;
}
public void setLkm_mobile(String lkm_mobile) {
this.lkm_mobile = lkm_mobile;
}
public String getLkm_memo() {
return lkm_memo;
}
public void setLkm_memo(String lkm_memo) {
this.lkm_memo = lkm_memo;
}
public String getLkm_position() {
return lkm_position;
}
public void setLkm_position(String lkm_position) {
this.lkm_position = lkm_position;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
1.4 书写hibernate配置文件
- Customer.hbm.xml
- LinkMan.hbm.xml
- hibernate.cfg.xml
1.5 测试
public class TestOne2Many {
@Test
public void testFunc() {
// 1. 获得session
Session session = HibernateUtils.openSession();
// 2. 开启事务
Transaction transaction = session.beginTransaction();
// 3.操作
LinkMan linkMan1 = new LinkMan();
linkMan1.setLkm_name("maHuaTeng");
LinkMan linkMan2 = new LinkMan();
linkMan2.setLkm_name("maYun");
Customer customer = new Customer();
customer.setCust_name("baidu");
// 表达一对多
customer.getLinkMen().add(linkMan1);
customer.getLinkMen().add(linkMan2);
// 表达多对一
linkMan1.setCustomer(customer);
linkMan2.setCustomer(customer);
session.save(customer);
session.save(linkMan1);
session.save(linkMan2);
transaction.commit();
session.close();
}
}
2. 一对多和多对一操作
2.1 客户添加联系人操作
@Test
// 客户添加联系人
public void testFunc02() {
// 1. 获得session
Session session = HibernateUtils.openSession();
// 2. 开启事务
Transaction transaction = session.beginTransaction();
// 3.操作
// 获得客户
Customer customer = session.get(Customer.class, 1l);
// 创建联系人
LinkMan linkMan = new LinkMan();
linkMan.setLkm_name("maFeiSi");
// 建立一对多关系
customer.getLinkMen().add(linkMan);
// 建立多对一关系
linkMan.setCustomer(customer);
session.save(customer);
session.save(linkMan);
transaction.commit();
session.close();
}
2.2 客户删除联系人
@Test
// 客户删除联系人
public void testFunc03() {
// 1. 获得session
Session session = HibernateUtils.openSession();
// 2. 开启事务
Transaction transaction = session.beginTransaction();
// 3.操作
// 获得客户
Customer customer = session.get(Customer.class, 1l);
// 创建联系人
LinkMan linkMan = session.get(LinkMan.class, 5l);
// 建立一对多关系
customer.getLinkMen().remove(linkMan);
// 建立多对一关系
linkMan.setCustomer(null);
transaction.commit();
session.close();
}
3. 级联操作
3.1 级联保存
@Test
// 级联保存
public void testFunc04() {
// 1. 获得session
Session session = HibernateUtils.openSession();
// 2. 开启事务
Transaction transaction = session.beginTransaction();
// 3.操作
// 获得客户
Customer customer = new Customer();
customer.setCust_name("baidu");
// 创建联系人
LinkMan linkMan1 = new LinkMan();
linkMan1.setLkm_name("maHuaTeng");
LinkMan linkMan2 = new LinkMan();
linkMan2.setLkm_name("maYun");
// 建立一对多关系
customer.getLinkMen().add(linkMan1);
customer.getLinkMen().add(linkMan2);
// 建立多对一关系
linkMan1.setCustomer(customer);
linkMan2.setCustomer(customer);
// 保存
session.save(customer);
transaction.commit();
session.close();
}
3.2 级联删除
@Test
// 级联删除
public void testFunc05() {
// 1. 获得session
Session session = HibernateUtils.openSession();
// 2. 开启事务
Transaction transaction = session.beginTransaction();
// 3.操作
// 获得客户
Customer customer = session.get(Customer.class, 1l);
session.delete(customer);
transaction.commit();
session.close();
}
3.3 联系人方进行级联保存
@Test
// 级联保存
public void testFunc06() {
// 1. 获得session
Session session = HibernateUtils.openSession();
// 2. 开启事务
Transaction transaction = session.beginTransaction();
// 3.操作
// 获得客户
Customer customer = new Customer();
customer.setCust_name("baidu");
// 创建联系人
LinkMan linkMan = new LinkMan();
linkMan.setLkm_name("maHuaTeng");
// 建立一对多关系
customer.getLinkMen().add(linkMan);
// 建立多对一关系
linkMan.setCustomer(customer);
// 保存
session.save(linkMan);
transaction.commit();
session.close();
}
4. 一对多和多对一进阶
4.1 inverse属性
- 用来过滤掉冗余的sql操作,让多的一方进行外键的维护,一的一方放弃外键的维护。
一的一方插入数据
Hibernate:
insert
into
t_customer
(cust_name, cust_source, cust_industry, cust_level, cust_linkman, cust_phone, cust_mobile)
values
(?, ?, ?, ?, ?, ?, ?)
Hibernate:
insert
into
cst_linkman
(lkm_gender, lkm_phone, lkm_name, lkm_email, lkm_qq, lkm_mobile, lkm_memo, lkm_position, lkm_cust_id)
values
(?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate:
insert
into
cst_linkman
(lkm_gender, lkm_phone, lkm_name, lkm_email, lkm_qq, lkm_mobile, lkm_memo, lkm_position, lkm_cust_id)
values
(?, ?, ?, ?, ?, ?, ?, ?, ?)
多的一方更新数据
Hibernate:
update
cst_linkman
set
lkm_cust_id=?
where
lkm_id=?
Hibernate:
update
cst_linkman
set
lkm_cust_id=?
where
lkm_id=?
- 外键字段在多的一方,所以多的一方不能放弃维护关系
- 提高关系维护的性能
- 如果客户放弃维护与联系人的关系,维护关系的代码可以省略
@Test
// 级联保存
public void testFunc06() {
// 1. 获得session
Session session = HibernateUtils.openSession();
// 2. 开启事务
Transaction transaction = session.beginTransaction();
// 3.操作
// 获得客户
Customer customer = new Customer();
customer.setCust_name("baidu");
// 创建联系人
LinkMan linkMan1 = new LinkMan();
linkMan1.setLkm_name("maHuaTeng");
LinkMan linkMan2 = new LinkMan();
linkMan2.setLkm_name("maYunYun");
// 建立一对多关系
// 如果客户放弃维护与联系人的关系,一的一方维护关系的代码可以省略
// customer.getLinkMen().add(linkMan1);
// customer.getLinkMen().add(linkMan2);
// 建立多对一关系
linkMan1.setCustomer(customer);
linkMan2.setCustomer(customer);
// 保存
session.save(customer);
session.save(linkMan1);
session.save(linkMan2);
transaction.commit();
session.close();
}
4.2 级联操作->删除Customer
在一对多关系中,有两种删除方案
- 设置一的一方也要维护外键关系,这样在删除一的一方表的时候,多的一方的外键会被置为null
- 直接设置级联关系cascade为级联删除
这样会把关联的表全部删除,属于危险操作
5. 多对多关系
5.1 创建模型
Snip20180810_39.png
5.2 创建实体类并书写对应类的配置文件
- Role
public class Role {
private Long role_id;
private String role_name;
private String role_memo;
//表达多对多
private Set users = new HashSet();
public Long getRole_id() {
return role_id;
}
public void setRole_id(Long role_id) {
this.role_id = role_id;
}
public String getRole_name() {
return role_name;
}
public void setRole_name(String role_name) {
this.role_name = role_name;
}
public String getRole_memo() {
return role_memo;
}
public void setRole_memo(String role_memo) {
this.role_memo = role_memo;
}
public Set getUsers() {
return users;
}
public void setUsers(Set users) {
this.users = users;
}
}
- User
public class User {
private Long user_id;
private String user_code;
private String user_name;
private String user_password;
private Character user_state;
//表达多对多
private Set roles = new HashSet();
public Long getUser_id() {
return user_id;
}
public void setUser_id(Long user_id) {
this.user_id = user_id;
}
public String getUser_code() {
return user_code;
}
public void setUser_code(String user_code) {
this.user_code = user_code;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_password() {
return user_password;
}
public void setUser_password(String user_password) {
this.user_password = user_password;
}
public Character getUser_state() {
return user_state;
}
public void setUser_state(Character user_state) {
this.user_state = user_state;
}
public Set getRoles() {
return roles;
}
public void setRoles(Set roles) {
this.roles = roles;
}
}
6. 多对多操作
6.1 保存
- 配置文件中,让role放弃维护关系
- 测试保存
// 保存员工以及角色
@Test
public void testFunc01() {
Session session = HibernateUtils.openSession();
Transaction transaction = session.beginTransaction();
User user1 = new User();
user1.setUser_name("zhangSan");
User user2 = new User();
user2.setUser_name("liSi");
Role role1 = new Role();
role1.setRole_name("student");
Role role2 = new Role();
role2.setRole_name("professor");
// 表达用户多对多关系
// 因为多对多关系中,是需要在关系表中插入数据,两次插入重复数据的操作会产生错误,所以只能由一方来维护关系,一方放弃维护关系
// user表达关系
user1.getRoles().add(role1);
user1.getRoles().add(role2);
user2.getRoles().add(role1);
user2.getRoles().add(role2);
// role表达关系
role1.getUsers().add(user1);
role1.getUsers().add(user2);
role2.getUsers().add(user1);
role2.getUsers().add(user2);
session.save(user1);
session.save(user2);
session.save(role1);
session.save(role2);
transaction.commit();
session.close();
}
6.2 为用户新增角色
// 为员工增加角色
@Test
public void testFunc02() {
Session session = HibernateUtils.openSession();
Transaction transaction = session.beginTransaction();
User user = session.get(User.class, 9l);
Role role = new Role();
role.setRole_name("assistant");
// 表达用户多对多关系
// user表达关系
user.getRoles().add(role);
// role表达关系
role.getUsers().add(user);
session.save(user);
session.save(role);
transaction.commit();
session.close();
}
6.3 级联操作和一对多是一样的
6.4 为用户解除角色
// 为员工解除角色
@Test
public void testFunc03() {
Session session = HibernateUtils.openSession();
Transaction transaction = session.beginTransaction();
User user = session.get(User.class, 9l);
Role role = session.get(Role.class, 6l);
// 表达用户多对多关系
// user表达关系
user.getRoles().remove(role);
transaction.commit();
session.close();
}
7. 为用户保存联系人
需求
Snip20180814_40.png
7.1 创建servlet
@WebServlet(name = "AddLinkManServlet")
public class AddLinkManServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
private LinkManService linkManService = new LinkManServiceImpl();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
LinkMan linkMan = new LinkMan();
try {
BeanUtils.populate(linkMan, request.getParameterMap());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
// 2.调用service保存客户
linkManService.save(linkMan);
// 3.重定向到客户列表
response.sendRedirect(request.getContextPath() + "/ListLinkManServlet");
}
}
配置web.xml
AddLinkManServlet
AddLinkManServlet
web.AddLinkManServlet
AddLinkManServlet
/AddLinkManServlet
7.2 创建Service和Service的实现类
public interface LinkManService {
public void save(LinkMan linkMan);
}
public class LinkManServiceImpl implements LinkManService {
private CustomerDao customerDao = new CustomerDaoImpl();
private LinkManDao linkManDao = new LinkManDaoImpl();
@Override
public void save(LinkMan linkMan) {
Session session = HibernateUtils.getCurrentSession();
// 打开事务
Transaction transaction = session.beginTransaction();
try {
Customer customer = customerDao.getCustomerById(linkMan.getCust_id());
linkMan.setCustomer(customer);
// customer.getLinkMen().add(linkMan); ?????
linkManDao.save(linkMan);
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
}
transaction.commit();
}
}
7.3为CustomerService提供根据id查找Customer的接口和实现方法
@Override
public Customer getCustomerById(Long cust_id) {
Session session = HibernateUtils.getCurrentSession();
return session.get(Customer.class, cust_id);
}
7.4 创建dao和dao的实现类
public interface LinkManDao {
public void save(LinkMan linkMan);
}
public class LinkManDaoImpl implements LinkManDao {
@Override
public void save(LinkMan linkMan) {
Session session = HibernateUtils.getCurrentSession();
session.save(linkMan);
}
}