Java programmers from stupid birds to cainiao () Talk about hibernate (7) one-to-many and multi-to-many relationship ing of hibernate itself

Source: Internet
Author: User

 

Welcome to other blogs on this topic:

 

About hibernate (10) Hibernate query sorting and component ing


Hibernate (11) hibernate composite primary key ing


Talk about hibernate (12) Hibernate query sorting component ing

Session caching mechanism of hibernate (13) and three object states

One-to-multiple relationship ing everyone understands that both sides of the relationship contain multiple references from the other side, but many of them do not understand what it means, first of all, I will explain what is one-to-many. In fact, it is easy to understand. one-to-many is itself containing multiple references, such as news categories, news includes sports news and political news. Sports News includes football news and basketball news. In fact, they all belong to news, but their names are different, next we will take the news category as an example to describe it:

First, let's take a look at the news class diagram:

Class diagram: Category

From the figure above, we can see that each news category has a set of parent and child categories, which are referenced by itself in both parent and child categories, in this way, we can establish a one-to-many object relationship.

 

Next let's take a look at the specific news entity class: category. Java

Public class category {private long ID; private string name; private category parentcategory; private set <Category> childcategories; public category (string name, category parentcategory, set <Category> childcategories) {This. name = Name; this. parentcategory = parentcategory; this. childcategories = childcategories;} public category () {}******** set, get method omitted}

After reading the specific object class, let's take a look at its specific configuration. In fact, there is nothing special about its configuration, it's just that his configuration contains one-to-many and multiple-to-one tags: he or she contains multiple-Party <set> tags. The <relative-to-one> tag of one party is also included:

Category. HBM. xml configuration file

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

Next, let's take a look at the example of adding, deleting, modifying, and querying in its own one-to-many relationship:

import java.util.HashSet;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;public class HibernateTest2{private static SessionFactory sessionFactory;static{try{sessionFactory = new Configuration().configure().buildSessionFactory();}catch (Exception ex){ex.printStackTrace();}}public static void main(String[] args){Session session = sessionFactory.openSession();Transaction tx = null;try{tx = session.beginTransaction();Category category1 = new Category("level1", null, new HashSet<Category>());Category category2 = new Category("level2", null, new HashSet<Category>());Category category3 = new Category("level2", null, new HashSet<Category>());Category category4 = new Category("level3", null, new HashSet<Category>());Category category5 = new Category("level3", null, new HashSet<Category>());Category category6 = new Category("level3", null, new HashSet<Category>());Category category7 = new Category("level3", null, new HashSet<Category>());category2.setParentCategory(category1);category3.setParentCategory(category1);category1.getChildCategories().add(category2);category1.getChildCategories().add(category3);category4.setParentCategory(category2);category5.setParentCategory(category2);category2.getChildCategories().add(category4);category2.getChildCategories().add(category5);category6.setParentCategory(category3);category7.setParentCategory(category3);category3.getChildCategories().add(category6);category3.getChildCategories().add(category7);Category category = (Category)session.get(Category.class, new Long(1));System.out.println(category.getChildCategories().iterator().next().getName());session.delete(category);tx.commit();}catch(Exception ex){if(null != tx){tx.rollback();}}finally{session.close();}}} 


In many practical development processes, many-to-many ing relationships are also common. The most obvious example is the examples of commonly used student course selection. A student can select multiple courses, one course can also be selected by multiple students, which forms a multi-to-many ing relationship. Now we will take a look at the multi-to-Multi-relationship ing of Student Course Selection examples. In multi-to-Multi- ing, Bidirectional Multi-to-multi-use is much more, and unidirectional multi-to-many is also relatively simple, so we will explain it in bidirectional multi-to-many mode.

First, write the necessary object classes and object ing files:

Let's take a brief look at the object class:

Student. Java

/** Student Entity class */public class student {private long ID; // Object ID (OID) Private string name; // name private string grade; // Private set <course> courses; // public student () {} // The parameter-free constructor ***** the set and get methods are omitted}

 

Course. Java

/** Course entity class */public class course {private long ID; // object identifier (OID) Private string name; // Course name private double credithours; // number of lessons private set <student> students; // set of students who have selected this course public course () {} // The parameter-free constructor ***** the set and get methods are omitted}

Next, write the object ing file:

Student. HBM. xml

<? XML version = "1.0" encoding = "UTF-8"?> <! Doctype hibernate-mapping public "-// hibernate/hibernate DTD ing DTD 3.0 // en" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 

Next, let's take a look at the key code for adding, deleting, modifying, and querying specific tests:

Add data test:

tran = session.beginTransaction();Student stu1 = new Student("xiaoli", "two");Student stu2 = new Student("xiaoming", "two");Student stu3 = new Student("xiaoqiang", "two");Course course1 = new Course("java", 3.0);Course course2 = new Course("c#", 5.0);//stuset.add(stu1);//stuset.add(stu2);//course1.setStudents(stuset);//session.save(course1);couset.add(course1);couset.add(course2);stu1.setCourses(couset);session.save(stu1);tran.commit();


Test conclusion: If you want to save the data successfully, whether it is the master or the prosecution, if you want to save the data once, you can save the data of both parties, you need to set the cascade attribute in the object configuration to all or save-update. Because it is set to all and contains Delete, deleting a piece of information will lead to the deletion of multiple or all information of the corresponding table. Therefore, you generally configure save-update.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.