周日自由敲代码总结

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liurongsheng123/article/details/79954105

hql连接查询

建立Customer类
public class Customer {
    private Long cust_id;
    private String cust_name;
    private String cust_phone;
    private String cust_linkman;
    private Set<LinkMan> linkMans = new HashSet<LinkMan>();

    public Set<LinkMan> getLinkMans() {
        return linkMans;
    }
    public void setLinkMans(Set<LinkMan> linkMans) {
        this.linkMans = linkMans;
    }
    public Customer() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Customer(Long cust_id, String cust_name, String cust_phone, String cust_linkman) {
        super();
        this.cust_id = cust_id;
        this.cust_name = cust_name;
        this.cust_phone = cust_phone;
        this.cust_linkman = cust_linkman;
    }
    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_phone() {
        return cust_phone;
    }
    public void setCust_phone(String cust_phone) {
        this.cust_phone = cust_phone;
    }
    public String getCust_linkman() {
        return cust_linkman;
    }
    public void setCust_linkman(String cust_linkman) {
        this.cust_linkman = cust_linkman;
    }
    @Override
    public String toString() {
        return "Customer [cust_id=" + cust_id + ", cust_name=" + cust_name + ", cust_phone=" + cust_phone
                + ", cust_linkman=" + cust_linkman + "]";
    }
}
配置Customer的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.lanou3g.bean">
    <class name="Customer" table="cust_customer">
        <id name="cust_id" column="cust_id">
            <generator class="native"></generator>
        </id>
        <property name="cust_id" column="cust_id"></property>
        <property name="lkm_mobile" column="lkm_mobile"></property>
        <property name="cust_linkman" column="cust_linkman"></property>
        <!-- 配置表示关系的容器 
            name 实体类中容器的名字 即保存字表中的数据
            column 表中的外键名 只有字表有外键名 参照主表的主键
            class 表示一对多关系中 从表的类名 (全类名) 如果上面已经写明在哪个类中 则可以不用写com.lanou3g.bean
            inverse: 默认维护外键的关系 默认值false
            inverse: 控制是否维护外键关系
            结语: inverse可以减少hibernate无用的操作 提高效率
            cascade: 级联操作 减少了代码
            save-update 级联保存(更新)
            delete 级联删除
            all = save-update + delete;
            建议:如果要用级联操作 就用save-update
            请慎用delete
        -->
        <set name="linkMans" cascade="delete">
            <key column="lkm_cust_id"></key>
            <one-to-many class="LinkMan" />
        </set>
    </class>
</hibernate-mapping>
建立LinkMan类
package com.lanou3g.bean;
public class LinkMan {
    private Long lkm_id;
    private String lkm_name;
    private Long lkm_cust_id;
    private String lkm_mobile;
    private String lkm_position;
    private Customer customer;

    public Customer getCustomer() {
        return customer;
    }
    public void setCustomer(Customer customer) {
        this.customer = customer;
    }
    public LinkMan() {
        super();
        // TODO Auto-generated constructor stub
    }
    public LinkMan(Long lkm_id, String lkm_name, Long lkm_cust_id, String lkm_mobile, String lkm_position) {
        super();
        this.lkm_id = lkm_id;
        this.lkm_name = lkm_name;
        this.lkm_cust_id = lkm_cust_id;
        this.lkm_mobile = lkm_mobile;
        this.lkm_position = lkm_position;
    }
    public Long getLkm_id() {
        return lkm_id;
    }
    public void setLkm_id(Long lkm_id) {
        this.lkm_id = lkm_id;
    }
    public String getLkm_name() {
        return lkm_name;
    }
    public void setLkm_name(String lkm_name) {
        this.lkm_name = lkm_name;
    }
    public Long getLkm_cust_id() {
        return lkm_cust_id;
    }
    public void setLkm_cust_id(Long lkm_cust_id) {
        this.lkm_cust_id = lkm_cust_id;
    }
    public String getLkm_mobile() {
        return lkm_mobile;
    }
    public void setLkm_mobile(String lkm_mobile) {
        this.lkm_mobile = lkm_mobile;
    }
    public String getLkm_position() {
        return lkm_position;
    }
    public void setLkm_position(String lkm_position) {
        this.lkm_position = lkm_position;
    }
    @Override
    public String toString() {
        return "LinkMan [lkm_id=" + lkm_id + ", lkm_name=" + lkm_name + ", lkm_cust_id=" + lkm_cust_id + ", lkm_mobile="
                + lkm_mobile + ", lkm_position=" + lkm_position + "]";
    }
}
配置LinkMan的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.lanou3g.bean">
    <class name="LinkMan" table="cust_LinkMan">
        <id name="lkm_id" column="lkm_id">
            <generator class="native"></generator>
        </id>
        <property name="lkm_name" column="lkm_name"></property>
        <property name="lkm_mobile" column="lkm_mobile"></property>
        <property name="lkm_position" column="lkm_position"></property>
        <!-- 
            配置表关系
            name:表示所关联的表的 自己在LinkMan这个类中定义的 属性名 即关联Customer表 LinkMan中定义为 customer
            column: 表示外键名 LinkMan表关联Customer表 联系为LinkMan中保存Customer中的客户id 从而将两者关联起来
            class: 表示对应关系中 对应的实体类名 即 Customer

            注意:无论是 外键 还是 主表的容器 都只能定义一次 不可以 上面property中与many-to-one中 同时定义
         -->
         <many-to-one name="customer" column="lkm_cust_id" class="Customer"></many-to-one>
    </class>
</hibernate-mapping>
连接查询
运行时将from 写成 form 导致错误
内连接查询(迫切 fetch)
不迫切 返回的是一个集合 集合中保存的是Object[]数组
数组中 保存的是你查询的两个对象
迫切 只返回一个对象(直接可以写泛型)
String hql = "from Customer c inner join fetch c.linkMans";


public class test3 {
    @Test
    public void fun1() {
        Configuration configuration = new Configuration().configure();
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();

        String hql = "from Customer c inner join c.linkMans";
        Query query = session.createQuery(hql);
        List<Object[]> list = query.list();
        for (Object[] objects : list) {
            System.out.println(Arrays.toString(objects));
        }

        transaction.commit();
        session.close();
    }
}
离线查询
所遇到的错误为 查询时id 为Long类型的 数字后面要加l 由于没加导致的错误

public void fun2() {
    创建离线对象(一般要用 就是在 servlet中使用)
    DetachedCriteria dc = DetachedCriteria.forClass(Customer.class);
    传递到dao层
    Session session = HibernateUtils.getSession();
    Transaction transaction = session.beginTransaction();
    dc.add(Restrictions.eq("cust_id", 2l));
    dc.add(Restrictions.eq("cust_name","嫦娥二号"));
    组装离线查询对象(赋值session)
    Criteria criteria = dc.getExecutableCriteria(session);
    List list = criteria.list();
    System.out.println(list);
    获取查询结果 并返回
    transaction.commit();
    session.close();
}

这里写图片描述

hql连接查询

建立Customer类
public class Customer {
    private Long cust_id;
    private String cust_name;
    private String cust_phone;
    private String cust_linkman;
    private Set<LinkMan> linkMans = new HashSet<LinkMan>();

    public Set<LinkMan> getLinkMans() {
        return linkMans;
    }
    public void setLinkMans(Set<LinkMan> linkMans) {
        this.linkMans = linkMans;
    }
    public Customer() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Customer(Long cust_id, String cust_name, String cust_phone, String cust_linkman) {
        super();
        this.cust_id = cust_id;
        this.cust_name = cust_name;
        this.cust_phone = cust_phone;
        this.cust_linkman = cust_linkman;
    }
    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_phone() {
        return cust_phone;
    }
    public void setCust_phone(String cust_phone) {
        this.cust_phone = cust_phone;
    }
    public String getCust_linkman() {
        return cust_linkman;
    }
    public void setCust_linkman(String cust_linkman) {
        this.cust_linkman = cust_linkman;
    }
    @Override
    public String toString() {
        return "Customer [cust_id=" + cust_id + ", cust_name=" + cust_name + ", cust_phone=" + cust_phone
                + ", cust_linkman=" + cust_linkman + "]";
    }
}
配置Customer的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.lanou3g.bean">
    <class name="Customer" table="cust_customer">
        <id name="cust_id" column="cust_id">
            <generator class="native"></generator>
        </id>
        <property name="cust_id" column="cust_id"></property>
        <property name="lkm_mobile" column="lkm_mobile"></property>
        <property name="cust_linkman" column="cust_linkman"></property>
        <!-- 配置表示关系的容器 
            name 实体类中容器的名字 即保存字表中的数据
            column 表中的外键名 只有字表有外键名 参照主表的主键
            class 表示一对多关系中 从表的类名 (全类名) 如果上面已经写明在哪个类中 则可以不用写com.lanou3g.bean
            inverse: 默认维护外键的关系 默认值false
            inverse: 控制是否维护外键关系
            结语: inverse可以减少hibernate无用的操作 提高效率
            cascade: 级联操作 减少了代码
            save-update 级联保存(更新)
            delete 级联删除
            all = save-update + delete;
            建议:如果要用级联操作 就用save-update
            请慎用delete
        -->
        <set name="linkMans" cascade="delete">
            <key column="lkm_cust_id"></key>
            <one-to-many class="LinkMan" />
        </set>
    </class>
</hibernate-mapping>
建立LinkMan类
package com.lanou3g.bean;
public class LinkMan {
    private Long lkm_id;
    private String lkm_name;
    private Long lkm_cust_id;
    private String lkm_mobile;
    private String lkm_position;
    private Customer customer;

    public Customer getCustomer() {
        return customer;
    }
    public void setCustomer(Customer customer) {
        this.customer = customer;
    }
    public LinkMan() {
        super();
        // TODO Auto-generated constructor stub
    }
    public LinkMan(Long lkm_id, String lkm_name, Long lkm_cust_id, String lkm_mobile, String lkm_position) {
        super();
        this.lkm_id = lkm_id;
        this.lkm_name = lkm_name;
        this.lkm_cust_id = lkm_cust_id;
        this.lkm_mobile = lkm_mobile;
        this.lkm_position = lkm_position;
    }
    public Long getLkm_id() {
        return lkm_id;
    }
    public void setLkm_id(Long lkm_id) {
        this.lkm_id = lkm_id;
    }
    public String getLkm_name() {
        return lkm_name;
    }
    public void setLkm_name(String lkm_name) {
        this.lkm_name = lkm_name;
    }
    public Long getLkm_cust_id() {
        return lkm_cust_id;
    }
    public void setLkm_cust_id(Long lkm_cust_id) {
        this.lkm_cust_id = lkm_cust_id;
    }
    public String getLkm_mobile() {
        return lkm_mobile;
    }
    public void setLkm_mobile(String lkm_mobile) {
        this.lkm_mobile = lkm_mobile;
    }
    public String getLkm_position() {
        return lkm_position;
    }
    public void setLkm_position(String lkm_position) {
        this.lkm_position = lkm_position;
    }
    @Override
    public String toString() {
        return "LinkMan [lkm_id=" + lkm_id + ", lkm_name=" + lkm_name + ", lkm_cust_id=" + lkm_cust_id + ", lkm_mobile="
                + lkm_mobile + ", lkm_position=" + lkm_position + "]";
    }
}
配置LinkMan的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.lanou3g.bean">
    <class name="LinkMan" table="cust_LinkMan">
        <id name="lkm_id" column="lkm_id">
            <generator class="native"></generator>
        </id>
        <property name="lkm_name" column="lkm_name"></property>
        <property name="lkm_mobile" column="lkm_mobile"></property>
        <property name="lkm_position" column="lkm_position"></property>
        <!-- 
            配置表关系
            name:表示所关联的表的 自己在LinkMan这个类中定义的 属性名 即关联Customer表 LinkMan中定义为 customer
            column: 表示外键名 LinkMan表关联Customer表 联系为LinkMan中保存Customer中的客户id 从而将两者关联起来
            class: 表示对应关系中 对应的实体类名 即 Customer

            注意:无论是 外键 还是 主表的容器 都只能定义一次 不可以 上面property中与many-to-one中 同时定义
         -->
         <many-to-one name="customer" column="lkm_cust_id" class="Customer"></many-to-one>
    </class>
</hibernate-mapping>
连接查询
运行时将from 写成 form 导致错误
内连接查询(迫切 fetch)
不迫切 返回的是一个集合 集合中保存的是Object[]数组
数组中 保存的是你查询的两个对象
迫切 只返回一个对象(直接可以写泛型)
String hql = "from Customer c inner join fetch c.linkMans";


public class test3 {
    @Test
    public void fun1() {
        Configuration configuration = new Configuration().configure();
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();

        String hql = "from Customer c inner join c.linkMans";
        Query query = session.createQuery(hql);
        List<Object[]> list = query.list();
        for (Object[] objects : list) {
            System.out.println(Arrays.toString(objects));
        }

        transaction.commit();
        session.close();
    }
}
离线查询
所遇到的错误为 查询时id 为Long类型的 数字后面要加l 由于没加导致的错误

public void fun2() {
    创建离线对象(一般要用 就是在 servlet中使用)
    DetachedCriteria dc = DetachedCriteria.forClass(Customer.class);
    传递到dao层
    Session session = HibernateUtils.getSession();
    Transaction transaction = session.beginTransaction();
    dc.add(Restrictions.eq("cust_id", 2l));
    dc.add(Restrictions.eq("cust_name","嫦娥二号"));
    组装离线查询对象(赋值session)
    Criteria criteria = dc.getExecutableCriteria(session);
    List list = criteria.list();
    System.out.println(list);
    获取查询结果 并返回
    transaction.commit();
    session.close();
}

多对多建立表关系

User类
import java.util.HashSet;
import java.util.Set;

/*
 * CREATE TABLE `sys_user` (
  `user_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '用户id',
  `user_code` varchar(32) NOT NULL COMMENT '用户账号',
  `user_name` varchar(64) NOT NULL COMMENT '用户名称',
  `user_password` varchar(32) NOT NULL COMMENT '用户密码',
  `user_state` char(1) NOT NULL COMMENT '1:正常,0:暂停',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
 */

public class User {
    private Long user_id;
    private String user_code;
    private String user_name;
    private String user_password;
    private String user_state;
    // 表示多对多关系
    private Set<Role> roles = new HashSet<>();

    public Set<Role> getRoles() {
        return roles;
    }
    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }
    public User() {
        super();
        // TODO Auto-generated constructor stub
    }
    public User(Long user_id, String user_code, String user_name, String user_password, String user_state) {
        super();
        this.user_id = user_id;
        this.user_code = user_code;
        this.user_name = user_name;
        this.user_password = user_password;
        this.user_state = user_state;
    }
    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 String getUser_state() {
        return user_state;
    }
    public void setUser_state(String user_state) {
        this.user_state = user_state;
    }
    @Override
    public String toString() {
        return "User [user_id=" + user_id + ", user_code=" + user_code + ", user_name=" + user_name + ", user_password="
                + user_password + ", user_state=" + user_state + "]";
    }
}
User类的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.lanou3g.bean">
    <class name="User" table="sys_user">
        <id name="user_id" column="user_id">
            <generator class="native"></generator>
        </id>
        <property name="user_code" column="user_code"></property>
        <property name="user_name" column="user_name"></property>
        <property name="user_password" column="user_password"></property>
        <property name="user_state" column="user_state"></property>

        <!-- 表示多对多关系 -->
        <!-- 
            name: User中对应容器的名(roles容器)
            table: 中间表的名字
            column: User中主键被引用当做外键(user_id)
            _____________________________________
            class: 与之对应的表的类名(全类名)
            column: 前面class(Role类)中主键被引用当做外键
         -->
        <set name="roles" table="sys_user_role" inverse="true">
            <key column="user_id"></key>
            <many-to-many class="Role" column="role_id"></many-to-many>
        </set>
    </class>
</hibernate-mapping>
Role类
package com.lanou3g.bean;

import java.util.HashSet;
import java.util.Set;

/*
CREATE TABLE `sys_role` (
         `role_id` bigint(32) NOT NULL AUTO_INCREMENT,
         `role_name` varchar(32) NOT NULL COMMENT '角色名称',
         `role_memo` varchar(128) DEFAULT NULL COMMENT '备注',
         PRIMARY KEY (`role_id`)
        ) ;*/
public class Role {
    private Long role_id;
    private String role_name;
    private String role_memo;
    private Set<Users> users = new HashSet<>();

    public Set<Users> getUsers() {
        return users;
    }
    public void setUsers(Set<Users> users) {
        this.users = users;
    }

    public Role() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Role(Long role_id, String role_name, String role_memo) {
        super();
        this.role_id = role_id;
        this.role_name = role_name;
        this.role_memo = role_memo;
    }
    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;
    }
    @Override
    public String toString() {
        return "Role [role_id=" + role_id + ", role_name=" + role_name + ", role_memo=" + role_memo + "]";
    }
}
Role类的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.lanou3g.bean">
    <class name="Role" table="role">
        <id name="role_id" column="role_id">
            <generator class="native"></generator>
        </id>
        <property name="role_name" column="role_name"></property>
        <property name="role_memo" column="role_memo"></property>
        <set name="users" table="sys_user_role" cascade="delete">
            <key column="role_id"></key>
            <many-to-many class="User" column="user_id"></many-to-many>
        </set>
    </class>
</hibernate-mapping>
public class Demo01 {
    /*
     * 添加一个客户 两个联系人
     * 
     * 对hibernate执行的sql语句的优化
     * 打印的插入语句 是linkman在维护自己的表
     * 并且在插入的时候 已经插入了外键(外键已经有了)
     * 
     * 打印的更新语句 是Customer来维护从而打印出来的
     * 
     * 这里对外键的维护 两个表都维护了一遍 造成了多余的sql语句操作
     */
    @Test
    public void fun1() {
        // 获取session 
        Session session = HibernateUtils.getSession();
        // 开启事务
        Transaction transaction = session.beginTransaction();
        // 创建客户
        Customer customer = new Customer();
        customer.setCust_name("蓝欧科技");
        // 创建联系人
        LinkMan l1 = new LinkMan();
        l1.setLkm_name("杨元虎");
        LinkMan l2 = new LinkMan();
        l2.setLkm_name("刘常凯");
        // 添加实体类中的关系
        // 把联系人添加到集合中
        customer.getLinkMans().add(l1);
        customer.getLinkMans().add(l2);
        // 给联系人设置客户
        l1.setCustomer(customer);
        l2.setCustomer(customer);
        // 保存到数据库
        session.save(customer);
        session.save(l1);
        session.save(l2);
        // 提交事务
        transaction.commit();
        // 关闭资源
        session.close();
    }
    // 为客户id为1的人删除联系人id为2
    @Test
    public void fun2() {
        Session session = HibernateUtils.getSession();
        Transaction transaction = session.beginTransaction();
        // 获取id为1的客户
        // 持久态 在事务提交的时候 如果该对象被修改了
        // 那么修改的数据会被同步到数据中
        Customer customer = session.get(Customer.class, 1l);
        // 获取id为2的联系人
        LinkMan linkMan = session.get(LinkMan.class, 2l);
        // 处理实体类中的关系
        customer.getLinkMans().remove(linkMan);
        linkMan.setCustomer(null);
        // 从数据库中删除
        session.delete(linkMan);

        //session.update(customer);
        transaction.commit();
        session.close();
    }
    // 为客户id为1 增加联系人
    @Test
    public void fun3() {
        Session session = HibernateUtils.getSession();
        Transaction transaction = session.beginTransaction();
        // 获取id为1的客户
        Customer customer = session.get(Customer.class, 1l);
        // 创建一个新的联系人
        LinkMan l3 = new LinkMan();
        l3.setLkm_name("龙哥");
        // 处理实体类中的关系
        l3.setCustomer(customer);   
        customer.getLinkMans().add(l3);
        // 保存到数据库
        session.save(l3);
        session.update(customer);
        transaction.commit();
        session.close();
    }
    // 新增客户 和 联系人(李胜运)
    // 级联操作作用:可以让你减少几行代码的工作量
    //            但是出问题 就是大事
    @Test
    public void fun4() {
        Session session = HibernateUtils.getSession();
        Transaction transaction = session.beginTransaction();

        Customer customer = new Customer();
        customer.setCust_name("博为峰");
        LinkMan linkMan = new LinkMan();
        linkMan.setLkm_name("李胜运");

        customer.getLinkMans().add(linkMan);
        linkMan.setCustomer(customer);

        session.save(customer);
        session.save(linkMan);

        transaction.commit();
        session.close();
    }
    // 级联 删除客户同时删除联系人
    @Test
    public void fun5() {
        Session session = HibernateUtils.getSession();
        Transaction transaction = session.beginTransaction();

        Customer customer = session.get(Customer.class, 1l);
        session.delete(customer);


        transaction.commit();
        session.close();
    }
}
package com.lanou3g.bean;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

/*
 * 测试多对多
 */
public class Demo02 {
    // 两个表 默认都会 维护自己的外键关系
    // 中间表 使用的联合主键 如果量张表都维护外键关系
    // 也就是说 都会对中间表进行操作 这时会重复插入相同的外键值
    // 注意: 所以多对多操作 必须要有一张表 放弃对外键关系的维护
    @Test
    public void fun1() {
        Session session = HibernateUtils.getSession();
        Transaction transaction = session.beginTransaction();

        User user1 = new User();
        User user2 = new User();

        Role role1 = new Role();
        Role role2 = new Role();

        user1.setUser_name("李胜运");
        user2.setUser_name("龙哥");

        role1.setRole_name("保安");
        role2.setRole_name("保洁");
        // 建立表关系
        user1.getRoles().add(role1);
        user1.getRoles().add(role2);
        user2.getRoles().add(role1);
        user2.getRoles().add(role2);

        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();
    }
    // 为id 为3的员工增加一个保洁的角色
    @Test
    public void fun2() {
        Session session = HibernateUtils.getSession();
        Transaction transaction = session.beginTransaction();

        User user = session.get(User.class, 3l);

        Role role = new Role();
        role.setRole_name("保洁");
        // 注意双侧关系都要添加上
        user.getRoles().add(role);
        role.getUsers().add(user);

//      session.save(user);
        session.save(role);

        transaction.commit();
        session.close();
    }
    // 为id为1的用户删除一个角色(id为2)
    @Test
    public void fun3() {
        Session session = HibernateUtils.getSession();
        Transaction transaction = session.beginTransaction();

        User user = session.get(User.class, 4l);
        Role role = session.get(Role.class, 3l);

        user.getRoles().remove(role);
        role.getUsers().remove(user);

//      session.save(role);
//      session.save(user);     

        transaction.commit();
        session.close();
    }
}
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页