Hibernate进阶学习3

Posted XDZY

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Hibernate进阶学习3相关的知识,希望对你有一定的参考价值。

Hibernate进阶学习3

测试hibernate的多表关联操作(一对多,多对一,多对多)

 

表之间的关系主要在类与元数据配置文件中体现

package com.hibernate.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 + "]";
    }

}
<?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.hibernate.domain">
    <!-- class元素: 配置实体与表的对应关系的 -->
    <class name="Customer" table="cst_customer">
        <!-- id元素:配置主键映射的属性 -->
        <id name="cust_id">
            <!-- generator:主键生成策略,每条数据录入时,主键的生成规则 -->
            <generator class="native"></generator>
        </id>
        <!-- property元素:除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属性:与我关联的对象完整类名 -->
        <!-- 级联操作:cascade
                save-update:级联保存更新
                delete:级联删除
                all:save-update+delete
            级联操作:简化操作,目的就是为了少写两行代码 -->
        <!-- inverse属性:配置关系是否维护
                true:customer不维护关系
                false(默认值):customer维护关系

             inverse属性:性能优化,提高关系维护的性能
             原则:无论怎么放弃,总有一方必须要维护关系
             一对多关系中:一的一方放弃,也只能一的一方放弃,多的一方不能放弃 -->
        <set name="linkMens" inverse="true" cascade="delete">
            <key column="lkm_cust_id"></key>
            <one-to-many class="LinkMan"/>
        </set>
    </class>
</hibernate-mapping>
package com.hibernate.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;
    }

}
<?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.hibernate.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属性:与我关联的对象完整类名 -->
        <!-- 级联操作:cascade
               save-update:级联保存更新
               delete:级联删除
               all:save-update+delete
           级联操作:简化操作,目的就是为了少写两行代码 -->
        <!-- 多的一方:不能放弃维护关系的,外键字段就在多的一方 -->
        <many-to-one name="customer" column="lkm_cust_id" class="Customer">
        </many-to-one>
    </class>
</hibernate-mapping>
package com.hibernate.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;
    }

}
<?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.hibernate.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>

        <!-- 使用inverse属性
                true:放弃维护外键关系
                false(默认值):维护关系

            结论:将来在开发中,如果遇到多对多关系,一定要选择一方放弃维护关系;
                 一般谁来放弃要看业务方向,例如录入员工时,需要为员工指定所属角色,
                 那么业务方向就是由员工维护角色,角色不需要维护与员工关系,角色放弃维护 -->
        <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>
    </class>
</hibernate-mapping>
package com.hibernate.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;
    }
}
<?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.hibernate.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:外键,我引用比人的外键列名 -->
        <!-- cascade级联操作:
                    save-update:级联保存更新
                    delete:级联删除
                    all:级联保存更新+级联删除
             结论:cascade简化代码书写,该属性使不使用无所谓,建议要用只用save-update
                   如果使用delete操作太过危险,尤其在多对多中,不建议使用 -->
        <set name="roles" table="sys_user_role" cascade="save-update">
            <key column="user_id"></key>
            <many-to-many class="Role" column="role_id"></many-to-many>
        </set>
    </class>
</hibernate-mapping>

 

测试一对多,多对一

package com.hibernate.onetomany;

import com.hibernate.domain.Customer;
import com.hibernate.domain.LinkMan;
import com.hibernate.utils.HibernateUtils;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

/**
 * @author: XDZY
 * @date: 2018/11/18 19:38
 * @description: 测试一对多操作
 */
public class Demo01 {
    /**
     * 添加客户和联系人信息
     */
    @Test
    public void test1() {
        //获取session
        Session session = HibernateUtils.openSession();
        //开启事务
        Transaction transaction = session.beginTransaction();

        /********************* 数据库操作 **********************/

        Customer customer = new Customer();
        customer.setCust_name("xdzy");

        LinkMan linkMan = new LinkMan();
        linkMan.setLkm_name("张三");
        LinkMan linkMan2 = new LinkMan();
        linkMan2.setLkm_name("李四");

        customer.getLinkMens().add(linkMan);
        customer.getLinkMens().add(linkMan2);

        linkMan.setCustomer(customer);
        linkMan2.setCustomer(customer);

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

        /*******************************************************/

        //提交事务
        transaction.commit();
        //关闭资源
        session.close();
    }

    /**
     * 为客户添加联系人
     */
    @Test
    public void test2() {
        //获取session
        Session session = HibernateUtils.openSession();
        //开启事务
        Transaction transaction = session.beginTransaction();

        /********************* 数据库操作 **********************/

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

        LinkMan linkMan = new LinkMan();
        linkMan.setLkm_name("王五");

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

        session.save(linkMan);

        /*******************************************************/

        //提交事务
        transaction.commit();
        //关闭资源
        session.close();
    }

    /**
     * 为客户移除联系人
     */
    @Test
    public void test3() {
        //获取session
        Session session = HibernateUtils.openSession();
        //开启事务
        Transaction transaction = session.beginTransaction();

        /********************* 数据库操作 **********************/

        Customer customer = session.get(Customer.class, 1L);
        LinkMan linkMan = session.get(LinkMan.class, 3L);

        customer.getLinkMens().remove(linkMan);
        linkMan.setCustomer(null);

        /*******************************************************/

        //提交事务
        transaction.commit();
        //关闭资源
        session.close();
    }
}
package com.hibernate.onetomany;

import com.hibernate.domain.Customer;
import com.hibernate.utils.HibernateUtils;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

/**
 * @author: XDZY
 * @date: 2018/11/19 8:05
 * @description: 测试级联操作
 */
public class Demo02 {
    /**
     * 删除用户时级联删除联系人;cascade:delete
     */
    @Test
    public void test1() {
        //获取session
        Session session = HibernateUtils.openSession();
        //开启事务
        Transaction transaction = session.beginTransaction();

        /********************* 数据库操作 **********************/

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

        /*******************************************************/

        //提交事务
        transaction.commit();
        //关闭资源
        session.close();
    }
}

 

测试多得多

package com.hibernate.manytomany;

import com.hibernate.domain.Role;
import com.hibernate.domain.User;
import com.hibernate.utils.HibernateUtils;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

/**
 * @author: XDZY
 * @date: 2018/11/19 10:15
 * @description: 测试多得多操作
 */
public class Demo01 {
    /**
     * 添加员工以及员工的职位
     */
    @Test
    public void test1() {
        //获取session
        Session session = HibernateUtils.openSession();
        //开启事务
        Transaction transaction = session.beginTransaction();

        /********************* 数据库操作 **********************/

        User user = new User();
        user.setUser_name("xdzy");
        User user1 = new User();
        user1.setUser_name("张三");

        Role role = new Role();
        role.setRole_name("学生");
        Role role1 = new Role();
        role1.setRole_name("老师");

        user.getRoles().add(role);
        user.getRoles().add(role1);
        user1.getRoles().add(role);
        user1.getRoles().add(role1);

        role.getUsers().add(user);
        role.getUsers().add(user1);
        role1.getUsers().add(user);
        role1.getUsers().add(user1);

        session.save(user);
        session.save(user1);
        session.save(role);
        session.save(role1);

        /*******************************************************/

        //提交事务
        transaction.commit();
        //关闭资源
        session.close();
    }

    /**
     * 为员工添加一个职位
     */
    @Test
    public void test2() {
        //获取session
        Session session = HibernateUtils.openSession();
        //开启事务
        Transaction transaction = session.beginTransaction();

        /********************* 数据库操作 **********************/

        User user = session.get(User.class, 1L);
        Role role = new Role();
        role.setRole_name("班主任");
        user.getRoles().add(role);
        session.save(user);

        /*******************************************************/

        //提交事务
        transaction.commit();
        //关闭资源
        session.close();
    }
}

 

以上是关于Hibernate进阶学习3的主要内容,如果未能解决你的问题,请参考以下文章

我的C语言学习进阶之旅解决 Visual Studio 2019 报错:错误 C4996 ‘fscanf‘: This function or variable may be unsafe.(代码片段

Hibernate学习笔记_02

SSH进阶之路Struts + Spring + Hibernate 进阶开端

我的OpenGL学习进阶之旅OpenGL ES 3.0实现了具有可编程着色功能的图形管线

我的OpenGL学习进阶之旅OpenGL ES 3.0实现了具有可编程着色功能的图形管线

Hibernate基础学习2