• 【Hibernate 多对多】


    HibernateManytoMany

    public class HibernateManytoMany {
    
        //演示维护第三张表
        @Test
        public void testTable2() {
            SessionFactory sessionFactory = null;
            Session session = null;
            Transaction tx = null;
            try {
                //得到sessionFactory
                sessionFactory = HibernateUtils.getSessionFactory();
                //得到session
                session = sessionFactory.openSession();
                //开启事务
                tx = session.beginTransaction();
    
                // 让某个用户没有有某个角色
                User user = session.get(User.class, 2);
                Role role = session.get(Role.class, 3);
    
                //2 从用户里面把角色去掉
                user.getSetRole().remove(role);
    
                //提交事务
                tx.commit();
    
            } catch (Exception e) {
                tx.rollback();
            } finally {
                session.close();
                //sessionFactory不需要关闭
                sessionFactory.close();
            }
        }
    
        //演示维护第三张表
        @Test
        public void testTable1() {
            SessionFactory sessionFactory = null;
            Session session = null;
            Transaction tx = null;
            try {
                //得到sessionFactory
                sessionFactory = HibernateUtils.getSessionFactory();
                //得到session
                session = sessionFactory.openSession();
                //开启事务
                tx = session.beginTransaction();
    
                // 让某个用户有某个角色
                //让lucy有经纪人角色
                //1 查询lucy和经纪人
                User lucy = session.get(User.class, 2);
                Role role = session.get(Role.class, 5);
    
                //2 把角色放到用户的set集合里面
                lucy.getSetRole().add(role);
    
                //提交事务
                tx.commit();
    
            } catch (Exception e) {
                tx.rollback();
            } finally {
                session.close();
                //sessionFactory不需要关闭
                sessionFactory.close();
            }
        }
    
        //演示多对多修级联保存
        @Test
        public void testDelete() {
            SessionFactory sessionFactory = null;
            Session session = null;
            Transaction tx = null;
            try {
                //得到sessionFactory
                sessionFactory = HibernateUtils.getSessionFactory();
                //得到session
                session = sessionFactory.openSession();
                //开启事务
                tx = session.beginTransaction();
    
                User user = session.get(User.class, 4);
                session.delete(user);
                //提交事务
                tx.commit();
    
            } catch (Exception e) {
                tx.rollback();
            } finally {
                session.close();
                //sessionFactory不需要关闭
                sessionFactory.close();
            }
        }
    
        //演示多对多修级联保存
        @Test
        public void testSave() {
            SessionFactory sessionFactory = null;
            Session session = null;
            Transaction tx = null;
            try {
                //得到sessionFactory
                sessionFactory = HibernateUtils.getSessionFactory();
                //得到session
                session = sessionFactory.openSession();
                //开启事务
                tx = session.beginTransaction();
    
                //添加两个用户,为每个用户添加两个角色
                //1 创建对象
                User user1 = new User();
                user1.setUser_name("lucy");
                user1.setUser_password("123");
    
                User user2 = new User();
                user2.setUser_name("mary");
                user2.setUser_password("456");
    
                Role r1 = new Role();
                r1.setRole_name("总经理");
                r1.setRole_memo("总经理");
    
                Role r2 = new Role();
                r2.setRole_name("秘书");
                r2.setRole_memo("秘书");
    
                Role r3 = new Role();
                r3.setRole_name("保安");
                r3.setRole_memo("保安");
    
                //2 建立关系,把角色放到用户里面
                // user1 -- r1/r2
                user1.getSetRole().add(r1);
                user1.getSetRole().add(r2);
    
                // user2 -- r2/r3
                user2.getSetRole().add(r2);
                user2.getSetRole().add(r3);
    
                //3 保存用户
                session.save(user1);
                session.save(user2);
    
                //提交事务
                tx.commit();
    
            } catch (Exception e) {
                tx.rollback();
            } finally {
                session.close();
                //sessionFactory不需要关闭
                sessionFactory.close();
            }
        }
    }

     User

    public class User {
        private Integer user_id;//用户id
        private String user_name;//用户名称
        private String user_password;//用户密码
    
        public Set<Role> getSetRole() {
            return setRole;
        }
    
        public void setSetRole(Set<Role> setRole) {
            this.setRole = setRole;
        }
    
        private Set<Role> setRole = new HashSet<>();
    
        public Integer getUser_id() {
            return user_id;
        }
    
        public void setUser_id(Integer user_id) {
            this.user_id = user_id;
        }
    
        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;
        }
    }
    View Code

    User.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>
        <class name="k.manytomany.User" table="t_user">
            <id name="user_id" column="user_id">
                <generator class="native"></generator>
            </id>
            <property name="user_name" column="user_name"></property>
            <property name="user_password" column="user_password"></property>
            <set name="setRole" table="user_role" cascade="save-update,delete">
                <key column="userid"></key>
                <many-to-many class="k.manytomany.Role" column="roleid"></many-to-many>
            </set>
        </class>
    </hibernate-mapping>

    Role

    public class Role {
        private Integer role_id;//角色id
        private String role_name;//角色名称
        private String role_memo;//角色描述
        private Set<User> setUser = new HashSet<>();
    
        public Set<User> getSetUser() {
            return setUser;
        }
    
        public void setSetUser(Set<User> setUser) {
            this.setUser = setUser;
        }
    
        public Integer getRole_id() {
            return role_id;
        }
    
        public void setRole_id(Integer 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;
        }
    }
    View Code

    Role.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>
        <class name="k.manytomany.Role" table="t_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="setUser" table="user_role" >
                <key column="roleid"></key>
                <many-to-many class="k.manytomany.User" column="userid"></many-to-many>
            </set>
        </class>
    </hibernate-mapping>

    HibernateUtils

    public class HibernateUtils {
    
        static Configuration cfg = null;
        static SessionFactory sessionFactory = null;
        //静态代码块实现
        static {
            //加载核心配置文件
            cfg = new Configuration();
            cfg.configure();
            sessionFactory = cfg.buildSessionFactory();
        }
    
        //提供返回与本地线程帮的session的方法
        public static Session getSessionobject() {
            return sessionFactory.getCurrentSession();
        }
    
        //提供方法返回sessionFactory
        public static SessionFactory getSessionFactory() {
            return sessionFactory;
        }
    
        public static void main(String[] args) {
    
        }
    }

    hibernate.cfg.xml

    <?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>
            <property name="hibernate.connection.url">jdbc:mysql:///hibernate_day01</property>
            <property name="hibernate.connection.useUnicode">true</property>
            <property name="hibernate.connection.characterEncoding">UTF-8</property>
            <property name="hibernate.connection.username">root</property>
            <property name="hibernate.connection.password">root3306</property>
            
            <!-- 第二部分: 配置hibernate信息  可选的-->
            <!-- 输出底层sql语句 -->
            <property name="hibernate.show_sql">true</property>
            <!-- 输出底层sql语句格式 -->
            <property name="hibernate.format_sql">true</property>
            <!-- hibernate帮创建表,需要配置之后 
                update: 如果已经有表,更新,如果没有,创建
            -->
            <property name="hibernate.hbm2ddl.auto">update</property>
            <!-- 配置数据库方言
                在mysql里面实现分页 关键字 limit,只能使用mysql里面
                在oracle数据库,实现分页rownum
                让hibernate框架识别不同数据库的自己特有的语句
             -->
            <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
            
            <!-- 第三部分: 把映射文件放到核心配置文件中 必须的-->
            <!--<mapping resource="k/entity/User.hbm.xml"/>-->
            <mapping resource="k/manytomany/User.xml"/>
            <mapping resource="k/manytomany/Role.xml"/>
        </session-factory>
    </hibernate-configuration>
  • 相关阅读:
    转载两篇文章之二(从程序员到CTO所要培养的六种能力)作者:阿蒙 原文:http://blog.csdn.net/harrymeng/archive/2007/02/07/1503931.aspx
    关于解决eclipse中的插件依赖
    GMF中控制Figure的大小和位置
    Sql server2005中如何格式化时间日期
    JavaScript创建对象的几种方式
    FCK编辑器焦点问题
    对引用类型的一点理解
    利用XML FOR PATH 合并分组信息
    [译]Silverlight中TreeView增删改查和拖放
    KeyedCollection<TKey, TItem>与IDictionary<TKey, TValue>的区别
  • 原文地址:https://www.cnblogs.com/kikyoqiang/p/12292638.html
Copyright © 2020-2023  润新知