宝马娱乐在线112222 > 网络应用 > hibernate框架学习笔记8:一对多关系案例,hibern

原标题:hibernate框架学习笔记8:一对多关系案例,hibern

浏览次数:188 时间:2019-10-06

hibernate框架学习笔记8:一对多关系案例,hibernate学习笔记

两个实体类:客户与联系人,一个客户可以有多个联系人

客户类:

图片 1

package domain;

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

//客户实体
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<LinkMan> linkMens = new HashSet<LinkMan>();

    public Set<LinkMan> getLinkMens() {
        return linkMens;
    }
    public void setLinkMens(Set<LinkMan> linkMens) {
        this.linkMens = linkMens;
    }
    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 + "]";
    }
}

View Code

联系人类:

图片 2

package domain;

//联系人实体
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 Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.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;
    }

}

View Code

 

Customer.hbm.xml:

图片 3

<?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="domain" >
    <class name="Customer" table="cst_customer" >
        <id name="cust_id"  >
            <generator class="native"></generator>
        </id>
        <property name="cust_name" column="cust_name" ></property>
        <property name="cust_source" column="cust_source" ></property>
        <property name="cust_industry" column="cust_industry" ></property>
        <property name="cust_level" column="cust_level" ></property>
        <property name="cust_linkman" column="cust_linkman" ></property>
        <property name="cust_phone" column="cust_phone" ></property>
        <property name="cust_mobile" column="cust_mobile" ></property>

        <!-- 集合,一对多关系,在配置文件中配置 -->
        <!-- 
            name属性:集合属性名
            column属性: 外键列名
            class属性: 与我关联的对象完整类名
         -->
        <set name="linkMens">
            <key column="lkm_cust_id" ></key>
            <one-to-many class="LinkMan" />
        </set>


    </class>
</hibernate-mapping>

View Code

 

LinkMan.hbm.xml:

图片 4

<?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="domain" >
    <class name="LinkMan" table="cst_linkman" >
        <id name="lkm_id"  >
            <generator class="native"></generator>
        </id>
        <property name="lkm_gender"  ></property>
        <property name="lkm_name"  ></property>
        <property name="lkm_phone"  ></property>
        <property name="lkm_email"  ></property>
        <property name="lkm_qq"  ></property>
        <property name="lkm_mobile"  ></property>
        <property name="lkm_memo"  ></property>
        <property name="lkm_position"  ></property>

        <!-- 多对一 -->
        <!-- 
            name属性:引用属性名
            column属性: 外键列名
            class属性: 与我关联的对象完整类名
         -->
        <many-to-one name="customer" column="lkm_cust_id" class="Customer"  ></many-to-one>
    </class>
</hibernate-mapping>

View Code

 

核心配置文件:

hibernate.cfg.xml:

图片 5

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- 数据库驱动 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- 数据库url -->
        <property name="hibernate.connection.url">jdbc:mysql:///hibernate</property>
        <!-- 数据库连接用户名 -->
        <property name="hibernate.connection.username">root</property>
        <!-- 数据库连接密码 -->
        <property name="hibernate.connection.password">xuyiqing</property>

        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- 将hibernate生成的sql语句打印到控制台 -->
        <property name="hibernate.show_sql">true</property>
        <!-- 将hibernate生成的sql语句格式化(语法缩进) -->
        <property name="hibernate.format_sql">true</property>

        <property name="hibernate.hbm2ddl.auto">update</property>
        <!-- 引入orm元数据 路径书写: 填写src下的路径 -->

        <property name="hibernate.connection.isolation">4</property>

        <!-- 指定session与当前线程绑定 -->
        <property name="hibernate.current_session_context_class">thread</property>

        <mapping resource="domain/Customer.hbm.xml" />
        <mapping resource="domain/LinkMan.hbm.xml" />

    </session-factory>
</hibernate-configuration>

View Code

 

自定义工具类:

图片 6

package utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtils {
    private static SessionFactory sf;

    static{
        //1 创建,调用空参构造
        Configuration conf = new Configuration().configure();
        //2 根据配置信息,创建 SessionFactory对象
         sf = conf.buildSessionFactory();
    }

    //获得session => 获得全新session
    public static Session openSession(){
                //3 获得session
                Session session = sf.openSession();

                return session;

    }
    //获得session => 获得与线程绑定的session
    public static Session getCurrentSession(){
        //3 获得session
        Session session = sf.getCurrentSession();

        return session;
    }    
}

View Code

 

测试类:

package oneTomany;

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

import domain.Customer;
import domain.LinkMan;
import utils.HibernateUtils;

//一对多|多对一关系操作
public class Demo {
    @Test
    //保存客户 以及客户 下的联系人
    public void fun1(){
        //1 获得session
        Session session = HibernateUtils.openSession();
        //2 开启事务
        Transaction tx = session.beginTransaction();
        //-------------------------------------------------
        //3操作
        Customer c = new Customer();
        c.setCust_name("腾讯");

        LinkMan lm1 = new LinkMan();
        lm1.setLkm_name("马化腾");

        LinkMan lm2 = new LinkMan();
        lm2.setLkm_name("张三");

        //表达一对多,客户下有多个联系人
        c.getLinkMens().add(lm1);
        c.getLinkMens().add(lm2);

        //表达多对一,联系人属于哪个客户
        lm1.setCustomer(c);
        lm2.setCustomer(c);


        session.save(c);
        session.save(lm1);
        session.save(lm2);
        //-------------------------------------------------
        //4提交事务
        tx.commit();
        //5关闭资源
        session.close();
    }

    @Test
    //为客户增加联系人
    public void fun2(){
        //1 获得session
        Session session = HibernateUtils.openSession();
        //2 开启事务
        Transaction tx = session.beginTransaction();
        //-------------------------------------------------
        //3操作
        //1> 获得要操作的客户对象
        Customer c = session.get(Customer.class,1l);
        //2> 创建联系人
        LinkMan lm1 = new LinkMan();
        lm1.setLkm_name("李四");
        //3> 将联系人添加到客户,将客户设置到联系人中
        c.getLinkMens().add(lm1);
        lm1.setCustomer(c);
        //4> 执行保存
        session.save(lm1);
        //-------------------------------------------------
        //4提交事务
        tx.commit();
        //5关闭资源
        session.close();
    }

    @Test
    //为客户删除联系人
    public void fun3(){
        //1 获得session
        Session session = HibernateUtils.openSession();
        //2 开启事务
        Transaction tx = session.beginTransaction();
        //-------------------------------------------------
        //3操作
        //1> 获得要操作的客户对象
        Customer c = session.get(Customer.class,1l);
        //2> 获得要移除的联系人
        LinkMan lm = session.get(LinkMan.class, 3l);
        //3> 将联系人从客户集合中移除
        c.getLinkMens().remove(lm);
        lm.setCustomer(null);
        //-------------------------------------------------
        //4提交事务
        tx.commit();
        //5关闭资源
        session.close();
    }

}

 

 

进阶操作一:cascade

上边fun1代码这一段:

        session.save(c);
        session.save(lm1);
        session.save(lm2);

这里发现:如果有很多个联系人,依次保存联系人代码量大,有没有一种方法,在保存客户的同时保存所有的联系人呢?

级联操作: cascade
save-update: 级联保存更新
delete:级联删除
all:save-update+delete
级联操作: 简化操作.目的就是为了少些两行代码.

配置文件:

        <set name="linkMens" cascade="save-update"  >
            <key column="lkm_cust_id" ></key>
            <one-to-many class="LinkMan" />
        </set>

 

这里就做到了级联保存

同样还有级联删除:删除客户,那么所有该客户所有联系人都将被删除

 

注意:客户和联系人配置文件都可以设置cascade属性

 

 

 

进阶操作二:

关系维护属性:inverse

多表操作的时候,会自动维护双方,影响效率,这里可以取消其中的维护以提高效率

在这里,客户一方可以不维护(即设置该属性为true)

        <set name="linkMens" inverse="true" cascade="delete"  >
            <key column="lkm_cust_id" ></key>
            <one-to-many class="LinkMan" />
        </set>

 

inverse属性: 配置关系是否维护.
true: customer不维护关系
false(默认值): customer维护关系

inverse属性: 性能优化.提高关系维护的性能.
原则: 无论怎么放弃,总有一方必须要维护关系.

注意:

一对多关系中: 一的一方放弃.也只能一的一方放弃.多的一方不能放弃.

http://www.bkjia.com/Javabc/1305124.htmlwww.bkjia.comtruehttp://www.bkjia.com/Javabc/1305124.htmlTechArticlehibernate框架学习笔记8:一对多关系案例,hibernate学习笔记 两个实体类:客户与联系人,一个客户可以有多个联系人 客户类: package domain...

hibernate框架学习笔记9:多对多关系案例,hibernate学习笔记

员工与角色案例:

一个员工可以是多种角色(总监,经理),一种角色可以是多个员工(保洁)

这里发现无法使用外键表达关系,多对多总是创建第三张表来维护关系

这张表至少两列,都是外键,分别引用两张表的主键

 

员工(用户)实体类:

图片 7

package domain;
//用户实体
import java.util.HashSet;
import java.util.Set;

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<Role> roles = new HashSet<Role>();
    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<Role> getRoles() {
        return roles;
    }
    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }



}

View Code

 

角色实体类:

图片 8

package domain;
//角色实体
import java.util.HashSet;
import java.util.Set;

public class Role {
    private Long role_id;
    private String role_name;
    private String role_memo;
    //表达多对多
    private Set<User> users = new HashSet<User>();
    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<User> getUsers() {
        return users;
    }
    public void setUsers(Set<User> users) {
        this.users = users;
    }

}

View Code

 

User.hbm.xml:

<?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="domain" >
    <class name="User" table="sys_user" >
        <id name="user_id"  >
            <generator class="native"></generator>
        </id>
        <property name="user_code"  ></property>
        <property name="user_name"  ></property>
        <property name="user_password"  ></property>
        <property name="user_state"  ></property>

        <!-- 多对多关系表达 -->
        <!-- 
            name: 集合属性名
            table: 配置中间表名
            key
             |-column:外键,别人引用"我"的外键列名
             class: 我与哪个类是多对多关系
             column:外键.我引用别人的外键列名
         -->
        <set name="roles" table="sys_user_role">
            <key column="user_id" ></key>
            <many-to-many class="Role" column="role_id" ></many-to-many>
        </set>

    </class>
</hibernate-mapping>

 

Role.hbm.xml:

图片 9

<?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="domain" >
    <class name="Role" table="sys_role" >
        <id name="role_id"  >
            <generator class="native"></generator>
        </id>
        <property name="role_name"  ></property>
        <property name="role_memo"  ></property>
        <set name="users" table="sys_user_role">
            <key column="role_id" ></key>
            <many-to-many class="User" column="user_id" ></many-to-many>
        </set>
    </class>
</hibernate-mapping>

View Code

 

核心配置文件:hibernate.cfg.xml:

图片 10

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- 数据库驱动 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- 数据库url -->
        <property name="hibernate.connection.url">jdbc:mysql:///hibernate</property>
        <!-- 数据库连接用户名 -->
        <property name="hibernate.connection.username">root</property>
        <!-- 数据库连接密码 -->
        <property name="hibernate.connection.password">xuyiqing</property>

        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- 将hibernate生成的sql语句打印到控制台 -->
        <property name="hibernate.show_sql">true</property>
        <!-- 将hibernate生成的sql语句格式化(语法缩进) -->
        <property name="hibernate.format_sql">true</property>

        <property name="hibernate.hbm2ddl.auto">update</property>
        <!-- 引入orm元数据 路径书写: 填写src下的路径 -->

        <property name="hibernate.connection.isolation">4</property>

        <!-- 指定session与当前线程绑定 -->
        <property name="hibernate.current_session_context_class">thread</property>
        <mapping resource="domain/User.hbm.xml" />
        <mapping resource="domain/Role.hbm.xml" />

    </session-factory>
</hibernate-configuration>

View Code

 

自定义工具类:

图片 11

package utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtils {
    private static SessionFactory sf;

    static{
        //1 创建,调用空参构造
        Configuration conf = new Configuration().configure();
        //2 根据配置信息,创建 SessionFactory对象
         sf = conf.buildSessionFactory();
    }

    //获得session => 获得全新session
    public static Session openSession(){
                //3 获得session
                Session session = sf.openSession();

                return session;

    }
    //获得session => 获得与线程绑定的session
    public static Session getCurrentSession(){
        //3 获得session
        Session session = sf.getCurrentSession();

        return session;
    }    
}

View Code

 

 

这里先写一段测试代码:

public void fun1(){
        //1 获得session
        Session session = HibernateUtils.openSession();
        //2 开启事务
        Transaction tx = session.beginTransaction();
        //-------------------------------------------------
        //3操作
        //1> 创建两个 User
        User u1 = new User();
        u1.setUser_name("张三");

        User u2 = new User();
        u2.setUser_name("李四");

        //2> 创建两个 Role
        Role r1 = new Role();
        r1.setRole_name("保洁");

        Role r2 = new Role();
        r2.setRole_name("保安");
        //3> 用户表达关系
        u1.getRoles().add(r1);
        u1.getRoles().add(r2);

        u2.getRoles().add(r1);
        u2.getRoles().add(r2);

        //4> 角色表达关系
        r1.getUsers().add(u1);
        r1.getUsers().add(u2);

        r2.getUsers().add(u1);
        r2.getUsers().add(u2);

        //5> 调用Save方法一次保存
        session.save(u1);
        session.save(u2);
        session.save(r1);
        session.save(r2);
        //-------------------------------------------------
        //4提交事务
        tx.commit();
        //5关闭资源
        session.close();
    }

 

看似很标准,不过运行会报错

原因:默认的inverse属性是维护的,两方关系都要维护,造成主键重复

解决办法:

1.改变代码:

    @Test
    //保存员工以及角色
    public void fun1(){
        //1 获得session
        Session session = HibernateUtils.openSession();
        //2 开启事务
        Transaction tx = session.beginTransaction();
        //-------------------------------------------------
        //3操作
        //1> 创建两个 User
        User u1 = new User();
        u1.setUser_name("张三");

        User u2 = new User();
        u2.setUser_name("李四");

        Role r1 = new Role();
        r1.setRole_name("保洁");

        Role r2 = new Role();
        r2.setRole_name("保安");
        u1.getRoles().add(r1);
        u1.getRoles().add(r2);
        u2.getRoles().add(r1);
        u2.getRoles().add(r2);
        session.save(u1);
        session.save(u2);
        session.save(r1);
        session.save(r2);
        //-------------------------------------------------
        //4提交事务
        tx.commit();
        //5关闭资源
        session.close();
    }

2.配置文件修改:

Role的配置文件:

        <set name="users" table="sys_user_role" inverse="true">
            <key column="role_id" ></key>
            <many-to-many class="User" column="user_id" ></many-to-many>
        </set>

这时候运行那一段代码就不会出错

 

结论: 将来在开发中,如果遇到多对多关系.一定要选择一方放弃维护关系.
一般谁来放弃要看业务方向. 例如录入员工时,需要为员工指定所属角色.
那么业务方向就是由员工维护角色. 角色不需要维护与员工关系.角色放弃维护

 

多对多同样有cascade属性:

cascade级联操作:
save-update: 级联保存更新
delete:级联删除
all:级联保存更新+级联删除

结论: cascade简化代码书写.该属性使不使用无所谓. 建议要用只用save-update.
如果使用delete操作太过危险.尤其在多对多中.不建议使用.

 

多对多的其他操作:

    @Test
    //为张三新增一个角色
    public void fun3(){
        //1 获得session
        Session session = HibernateUtils.openSession();
        //2 开启事务
        Transaction tx = session.beginTransaction();
        //-------------------------------------------------
        //3操作
        //1> 获得张三用户
        User user = session.get(User.class, 3l);
        //2> 创建总经理角色
        Role r = new Role();
        r.setRole_name("总经理");
        //3> 将角色添加到用户中
        user.getRoles().add(r);
        //4> 将角色转换为持久化
        session.save(r);
        //-------------------------------------------------
        //4提交事务
        tx.commit();
        //5关闭资源
        session.close();
    }

    @Test
    //为张三解除一个角色
    public void fun4(){
        //1 获得session
        Session session = HibernateUtils.openSession();
        //2 开启事务
        Transaction tx = session.beginTransaction();
        //-------------------------------------------------
        //3操作
        //1> 获得郝强勇用户
        User user = session.get(User.class, 3l);
        //2> 获得要操作的角色对象(保洁,保安)
        Role r1 = session.get(Role.class, 1l);
        Role r2 = session.get(Role.class, 2l);
        //3> 将角色从用户的角色集合中移除
        user.getRoles().remove(r1);
        user.getRoles().remove(r2);

        //-------------------------------------------------
        //4提交事务
        tx.commit();
        //5关闭资源
        session.close();
    }

 

 

这里是一对多的文章,对比后更有收获

http://www.cnblogs.com/xuyiqing/p/8453165.html

http://www.bkjia.com/Javabc/1305121.htmlwww.bkjia.comtruehttp://www.bkjia.com/Javabc/1305121.htmlTechArticlehibernate框架学习笔记9:多对多关系案例,hibernate学习笔记 员工与角色案例: 一个员工可以是多种角色(总监,经理),一种角色可以是多...

本文由宝马娱乐在线112222发布于网络应用,转载请注明出处:hibernate框架学习笔记8:一对多关系案例,hibern

关键词:

上一篇:没有了

下一篇:没有了