zoukankan      html  css  js  c++  java
  • hibernate多对多关联关系

    先来说下一对多的自关联

    首先实体类TreeNode.java

    package com.jt4.entity;
    
    import java.util.HashSet;
    import java.util.Set;
    
    public class TreeNode {
        private Integer nodeId;
        private String nodeName;
        private Integer treeNodeType;
        private Integer position;
        private String url;
        private TreeNode parent;
        private Set<TreeNode> children = new HashSet<TreeNode>();
        private Integer initChildren = 0;
    
        public Integer getNodeId() {
            return nodeId;
        }
    
        public void setNodeId(Integer nodeId) {
            this.nodeId = nodeId;
        }
    
        public String getNodeName() {
            return nodeName;
        }
    
        public void setNodeName(String nodeName) {
            this.nodeName = nodeName;
        }
    
        public Integer getTreeNodeType() {
            return treeNodeType;
        }
    
        public void setTreeNodeType(Integer treeNodeType) {
            this.treeNodeType = treeNodeType;
        }
    
        public Integer getPosition() {
            return position;
        }
    
        public void setPosition(Integer position) {
            this.position = position;
        }
    
        public String getUrl() {
            return url;
        }
    
        public void setUrl(String url) {
            this.url = url;
        }
    
        public TreeNode getParent() {
            return parent;
        }
    
        public void setParent(TreeNode parent) {
            this.parent = parent;
        }
    
        public Set<TreeNode> getChildren() {
            return children;
        }
    
        public void setChildren(Set<TreeNode> children) {
            this.children = children;
        }
    
        public Integer getInitChildren() {
            return initChildren;
        }
    
        public void setInitChildren(Integer initChildren) {
            this.initChildren = initChildren;
        }
    
    //    @Override
    //    public String toString() {
    //        return "TreeNode [nodeId=" + nodeId + ", nodeName=" + nodeName + ", treeNodeType=" + treeNodeType
    //                + ", position=" + position + ", url=" + url + ", children=" + children + "]";
    //    }
    
        @Override
        public String toString() {
            return "TreeNode [nodeId=" + nodeId + ", nodeName=" + nodeName + ", treeNodeType=" + treeNodeType
                    + ", position=" + position + ", url=" + url + ", parent=" + parent + ", children=" + children
                    + ", initChildren=" + initChildren + "]";
        }
        
    
    }

     映射文件TreeNode.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>
        <class name="com.jt4.entity.TreeNode" table="t_hibernate_sys_tree_node">
            <id name="nodeId" type="java.lang.Integer" column="tree_node_id">
                <generator class="increment" />
            </id>
            <property name="nodeName" type="java.lang.String"
                column="tree_node_name">
            </property>
            <property name="treeNodeType" type="java.lang.Integer"
                column="tree_node_type">
            </property>
            <property name="position" type="java.lang.Integer"
                column="position">
            </property>
            <property name="url" type="java.lang.String"
                column="url">
            </property>
            
            <many-to-one name="parent" class="com.jt4.entity.TreeNode" column="parent_node_id"/>
            
            <set name="children" cascade="save-update" inverse="true">
                <key column="parent_node_id"></key>
                <one-to-many class="com.jt4.entity.TreeNode"/>
            </set>
        </class>
    </hibernate-mapping>

    dao方法TreeNodeDao.java

    package com.jt4.dao;
    
    import org.hibernate.Hibernate;
    import org.hibernate.Session;
    import org.hibernate.Transaction;
    
    import com.jt2.util.SessionFactoryUtils;
    import com.jt4.entity.TreeNode;
    
    public class TreeNodeDao {
        public TreeNode load(TreeNode treeNode) {
            Session session = SessionFactoryUtils.openSession();
            Transaction transaction = session.beginTransaction();
            TreeNode t = session.load(TreeNode.class, treeNode.getNodeId());
            if(t != null && new Integer(1).equals(treeNode.getInitChildren())) {
                Hibernate.initialize(t.getChildren());
                Hibernate.initialize(t.getParent());
            }
            transaction.commit();
            session.close();
            return t;
        }
    }

    测试TreeNodeDaoTest.java

    package com.jt4.dao;
    
    import org.junit.Test;
    
    import com.jt4.entity.TreeNode;
    
    public class TreeNodeDaoTest {
        private TreeNodeDao treeNodeDao = new TreeNodeDao();
    
        @Test
        public void testLoad() {
            TreeNode treeNode = new TreeNode();
            treeNode.setNodeId(6);
            treeNode.setInitChildren(1);
            
            TreeNode t = this.treeNodeDao.load(treeNode);
            System.out.println(t);
            System.out.println(t.getParent());
            System.out.println(t.getChildren());
        }
    
    }

    下面是多对多关联关系

    Category.java

    package com.jt4.entity;
    
    import java.io.Serializable;
    import java.util.HashSet;
    import java.util.Set;
    
    public class Category implements Serializable{
    //    category_id int primary key auto_increment,
    //       category_name varchar(50) not null
        private Integer categoryId;
        private String categoryName;
        private Set<Book> books = new HashSet<Book>();
        public Integer getCategoryId() {
            return categoryId;
        }
        public void setCategoryId(Integer categoryId) {
            this.categoryId = categoryId;
        }
        public String getCategoryName() {
            return categoryName;
        }
        public void setCategoryName(String categoryName) {
            this.categoryName = categoryName;
        }
        public Set<Book> getBooks() {
            return books;
        }
        public void setBooks(Set<Book> books) {
            this.books = books;
        }
        @Override
        public String toString() {
            return "Category [categoryId=" + categoryId + ", categoryName=" + categoryName + "]";
        }
        
    }

    Book.java

    package com.jt4.entity;
    
    import java.io.Serializable;
    import java.util.HashSet;
    import java.util.Set;
    
    public class Book implements Serializable{
    //    book_id int primary key auto_increment,
    //       book_name varchar(50) not null,
    //       price float not null
        private Integer bookId;
        private String bookName;
        private Float price;
        
        private Set<Category> categories = new HashSet<Category>();
        private Integer initCategories = 0;
    
        public Integer getInitCategories() {
            return initCategories;
        }
    
        public void setInitCategories(Integer initCategories) {
            this.initCategories = initCategories;
        }
    
        public Integer getBookId() {
            return bookId;
        }
    
        public void setBookId(Integer bookId) {
            this.bookId = bookId;
        }
    
        public String getBookName() {
            return bookName;
        }
    
        public void setBookName(String bookName) {
            this.bookName = bookName;
        }
    
        public Float getPrice() {
            return price;
        }
    
        public void setPrice(Float price) {
            this.price = price;
        }
    
        public Set<Category> getCategories() {
            return categories;
        }
    
        public void setCategories(Set<Category> categories) {
            this.categories = categories;
        }
    
        @Override
        public String toString() {
            return "Book [bookId=" + bookId + ", bookName=" + bookName + ", price=" + price + "]";
        }
    
        public Book(Integer bookId, String bookName) {
            super();
            this.bookId = bookId;
            this.bookName = bookName;
        }
    
        public Book() {
            super();
        }
        
        
    }

    book.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>
        <class name="com.jt4.entity.Book" table="t_hibernate_book">
            <cache usage="read-only" region="com.zking.five.entity.Book"/>
            <id name="bookId" type="java.lang.Integer" column="book_id">
                <generator class="increment" />
            </id>
            <property name="bookName" type="java.lang.String"
                column="book_name">
            </property>
            <property name="price" type="java.lang.Float"
                column="price">
            </property>
            <!-- 
            set标签
                 table:对应的是中间表,没有实体类的,意味着靠两张主表对应的映射文件联合管理数据
                 name:当前映射文件对应的实体类对应的属性
                 cascade:级联新增修改,说白了就是当前实体类对应的表删除能否影响到关联表的数据
                 inberse:中间表的数据维护的权利交给对方                                                 
            key标签
                 column:当前表t_hibernate_book_category的主键book_id在中间表的列段bid
                 many-to-many:
                 column:代表中间表对应的除去当前表t_hibernate_book的非主键的中间列段cid
                 class:cid对应的类      
             -->
            <set table="t_hibernate_book_category" name="categories" cascade="save-update" inverse="true">
                <!-- one -->
                <key column="bid"></key>
                <!-- many -->
                <many-to-many column="cid" class="com.jt4.entity.Category"></many-to-many>
            </set>
        </class>
    </hibernate-mapping>

    category.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>
        <class name="com.jt4.entity.Category" table="t_hibernate_category">
            <id name="categoryId" type="java.lang.Integer" column="category_id">
                <generator class="increment" />
            </id>
            <property name="categoryName" type="java.lang.String"
                column="category_name">
            </property>
            
            <set table="t_hibernate_book_category" name="books" cascade="save-update" inverse="true">
                <key column="cid"></key>
                <many-to-many column="bid" class="com.jt4.entity.Book"></many-to-many>
            </set>
        </class>
    </hibernate-mapping>

    这些配置好了要在hibernate.cfg.xml中配置

    <!--一对多自关联  -->
            <mapping resource="com/jt4/entity/TreeNode.hbm.xml"/>
            <!-- 多对多 -->
            <mapping resource="com/jt4/entity/book.hbm.xml"/>
            <mapping resource="com/jt4/entity/Category.hbm.xml"/>

    BookDao.java

    package com.jt4.dao;
    
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import org.hibernate.Hibernate;
    import org.hibernate.Session;
    import org.hibernate.Transaction;
    import org.hibernate.query.Query;
    
    import com.jt2.util.SessionFactoryUtils;
    import com.jt4.entity.Book;
    import com.jt4.entity.Category;
    import com.mysql.jdbc.StringUtils;
    
    public class BookDao{
        public Integer addBook(Book book) {
            Session session = SessionFactoryUtils.openSession();
            Transaction transaction = session.beginTransaction();
            Integer bid = (Integer) session.save(book);
            transaction.commit();
            session.close();
            return bid;
        }
        
        public Integer addCategory(Category category) {
            Session session = SessionFactoryUtils.openSession();
            Transaction transaction = session.beginTransaction();
            Integer cid = (Integer) session.save(category);
            transaction.commit();
            session.close();
            return cid;
        }
        
        public Category getCategory(Category category) {
            Session session = SessionFactoryUtils.openSession();
            Transaction transaction = session.beginTransaction();
            Category c = session.get(Category.class, category.getCategoryId());
            transaction.commit();
            session.close();
            return c;
        }
        
        public Book getBook(Book book) {
            Session session = SessionFactoryUtils.openSession();
            Transaction transaction = session.beginTransaction();
            Book b = session.get(Book.class, book.getBookId());
            if (b != null && new Integer(1).equals(book.getInitCategories())) {
                Hibernate.initialize(b.getCategories());
            }
            transaction.commit();
            session.close();
            return b;
        }
        
        public void delBook(Book book) {
            Session session = SessionFactoryUtils.openSession();
            Transaction transaction = session.beginTransaction();
            session.delete(book);
            transaction.commit();
            session.close();
        }
        
        public void delCategory(Category category) {
            Session session = SessionFactoryUtils.openSession();
            Transaction transaction = session.beginTransaction();
            Category c = session.get(Category.class, category.getCategoryId());
            if(c!=null) {
                for (Book b : c.getBooks()) {
    //                通过在被控方通过主控方来解除关联关系,最后被控方再做删除
                    b.getCategories().remove(c);
                }
            }
            session.delete(c);
            transaction.commit();
            session.close();
        }
        
        
    }

    测试BookDaoTest.java

    package com.jt4.dao;
    
    import org.junit.Test;
    
    import com.jt4.entity.Book;
    import com.jt4.entity.Category;
    
    public class BookDaoTest {
        private BookDao bookDao = new BookDao();
    
        @Test
        public void testGetBook() {
            Book book = new Book();
            book.setBookId(8);
            book.setInitCategories(1);
            Book b = this.bookDao.getBook(book );
            System.out.println(b.getBookName());
            System.out.println(b.getCategories());
        }
        
        /**
         * book.hbm.xml    inverse=fasle
         * category.hbm.xml inverse=true
         * 数据添加正常
         * 书籍表、桥接表各新增一条数据
         */
        @Test
        public void test1() {
            Book book = new Book();
            book.setBookName("jt5555555");
            book.setPrice(10f);
            Category category = new Category();
            category.setCategoryId(5);
    //        直接将category对象加入到新建的book中是错误的,因为此时的category是临时态的,hibernate是不会管理的
    //        book.getCategories().add(category);
            Category c = this.bookDao.getCategory(category);
            
    //        c.getBooks().add(book);
            book.getCategories().add(c);
            this.bookDao.addBook(book);
        }
    
        /**
         * book.hbm.xml    inverse=false
         * category.hbm.xml inverse=true
         * 只增加书籍表数据
         * 桥接表不加数据
         * 原因:双方都没有去维护关系
         */
        @Test
        public void test2() {
            Book book = new Book();
            book.setBookName("jt66666666");
            book.setPrice(10f);
            Category category = new Category();
            category.setCategoryId(5);
            Category c = this.bookDao.getCategory(category);
            
            book.getCategories().add(c);
            this.bookDao.addBook(book);
    //        c.getBooks().add(book);
        }
        
        
    }

     

  • 相关阅读:
    网页一屏到底有多大 1024*768 800*600 网页设计大小 网页设计尺寸
    去掉VS2005中水晶报表的登录界面(ZT)
    Visual Studio 2005 IDE 技巧和窍门
    asp.net大页面载入时以进度条显示zt
    从webservice读取string[]至downlist,增加onchange事件,更改相关显示。
    在asp.net Sql server (可以是存储过程)中使用事务回滚
    得到页面所有的form内对象数值——————为一个控件加一个客户端属性
    Agile Web Development 4th ed. Can't mass assign.error
    Ubuntu12.04中安装和配置Java JDK(转)
    Javascript没有块级作用域
  • 原文地址:https://www.cnblogs.com/ztbk/p/11313610.html
Copyright © 2011-2022 走看看