Mapping relationship of Hibernate

Posted by pradee on Tue, 11 Jun 2019 18:56:38 +0200

Hibernate mapping relationship

1. Description of mapping file

1.1 Noun Interpretation

  1. Relationship: The state in which things interact and relate with each other.
  2. Association: Noun: denotes the relationship between objects (database tables); verb: associates objects (database tables) in some way.
  3. Mapping: Transforming one form into another, including relationships.
  4. Cascade: One of the parties involved will take some action while the other will take some action.
  5. Value type: Object is not database identical, belongs to an entity instance whose persistent state is embedded in the table rows of all entities, and has no identifier.
  6. Entity type: Has a database identifier.

1.1 File Function Description

  1. Mapping class (.Java)

    Mapping class (*.java): It describes the structure of a database table, and the fields in the table are described as attributes in the class. It will be possible to map records in the table into objects of this class in the future.
  2. Mapping file (.hbm.xml)

    Mapping file (*.hbm.xml): It specifies the relationship between the database table and the mapping class, including the mapping class and the database table, the table field and class attribute type, and the table field and class attribute name.
  3. Database configuration file (.properties/.cfg.xml)

    Database configuration file (.properties/.cfg.xml): It specifies the connection information needed to connect to the database, such as which database to connect to, the user name of the login database, the login password, and the connection string.Of course, you can also put the address mapping information for the mapping class here

2. Mapping Relationships

outline

  1. One-to-one associations are divided into primary key associations and foreign key associations

    Primary key associations: There is no need to add additional fields, only the primary key associations of the primary table and the secondary table, where the values of the two primary keys are the same.
    
    Foreign key associations: A secondary table has an additional field associated with the primary table, or both tables have additional fields associated with the corresponding table.
  2. One-to-many

    Many-to-one Association mapping: Adding a foreign key to one end of a multiple end maintains a multiple-to-one relationship
     One-to-many Association mapping: Adding a foreign key to one end of a multiple end maintains a one-to-many relationship
  3. Many-to-many

    It is not ideal in terms of operation and performance, so many-to-many mapping is used less and the best one-to-many object model is used in practice; hibernate will create intermediate association tables for us and convert them into two one-to-many

2.1, one-to-one

One-to-one relationships between two objects, such as husband-wife User and Acount, where one user corresponds to one Account, have two strategies for mapping one-to-one associations

2.1.1, Primary Key Association (not important)

2.1.1.1. Core Ideas

That is, two objects have the same primary key value to indicate a one-to-one correspondence between them; database tables do not have additional fields to maintain the relationship between them, but are related only by the primary key of the table, that is, the primary key of one table establishes a one-to-one association by referencing the primary key of another table

2.1.1.2, Configuration
Configuration files are one-to-one, and constrained="true" is added to the one-to-one attribute of the secondary table to indicate constrained.So change the id of the secondary table to foreign and add the attribute parameter
2.1.1.3, sample code
  1. object model

  2. Wife Classes and Profiles
    1. java class

      private String wid;
      private String name;
    2. hbm.xml configuration

      <class name="Wifi" table="TB_WIFI">
            <id name="wid" column="WID">
                <generator class="uuid"/>
            </id>
            <property name="name" column="NAME"/>
      </class>
  3. Husband class and configuration
    1. java class

      private String hid;
      private String name;
      private Wifi wifi;
    2. hbm.xml configuration

      <class name="Husband" table="TB_HUSBAND">
            <id name="hid" column="HID">
                <generator class="foreign">
                    <param name="property">wifi</param>
                </generator>
            </id>
            <property name="name" column="NAME"/>
               constrained="true" means that a table of the corresponding type (wifi table) for this attribute (name="wifi") forms a foreign key constraint on the Husband table.
            <one-to-one name="wifi" class="Wifi" constrained="true"/>
        </class>
    3. Test Code

      //Load using Hibernate.cfg.xml file under default resources
      Configuration cfg = new Configuration().configure();
      //Create Session Factory Class
      SessionFactory factory = cfg.buildSessionFactory();
      Session session = null;
      Transaction transaction = null;
      //Opening session is equivalent to jdbc's connection object
      session = factory.openSession();
      //Open Transaction
      transaction = session.beginTransaction();
      //Initialize data
      Husband husband = new Husband();
      husband.setName("King");
      Wifi wifi = new Wifi();
      wifi.setName("Ha-ha");
      wifi.setHusband(husband);
      husband.setWifi(wifi);
      //Persist Object
      session.save(husband);
      //Submit Transaction
      transaction.commit();
      //Close session
      session.close();
      Queries are queried by classes with primary and foreign keys
       Core Code
      Husband husband = em.find(Husband.class, "402882215d1d84d8015d1d84da0e0000");
      Output Results
       Husband{hid='402882215d1d84d8015d1d84da0e0000', name='King', wifi=Wifi{wid='402882215d1d8415d1d84da0e0000', name='Ha'}

2.1.1.4, Summary

  1. Because of the primary key association, which is actually related to two tables through a primary key, the primary key values of the associated probability must be kept in sync, which means that we only need to set one table, such as a wifi table, to set the primary key generator, and another table, the Husband table, which has the same primary key values as the other table.

  2. Although there is a reciprocal reference relationship between Husband and Wife classes, there is no reference relationship between Husband and Wife tables on the database side, but when we save the User object, if the wife attribute value in Husband is not NULL, hibernate will use the primary key value generated by the primary key generator used in wife.hbm.xml as the primary key value for inserting records into Husband and wife tables, which will be preservedSynchronization of primary key values holding associated records (as indicated by the output SQL statement, this is handled by Hibernate and unknown to the database side)

  3. constrained attribute in (association constraint)

    1. The constrained attribute value defaults to false, when constrained is false, there is no reference relationship between the two generated tables, and the immediate loading policy is used if the constrained attribute value is changed to true

    2. If the table does not exist when data is inserted

      1. If constrained in wife.hbm.xml is true, create two tables and establish a reference relationship, the id in the WiFi table will be the foreign key to the id in the Husband table (deleting wife.setHusbnad(husband) above will naturally throw an exception, because Wifi's id refers to the id in Husband the two primary key values are synchronized); the resulting two tables structure and reference relationship are
      2. If constrained in husband.hbm.xml establishes two tables for true and establishes a reference relationship The id in Husband table refers to the id in wifi table, then the object saved should be a wifi object
      3. If both constrained are true, two mutually referenced tables, users and idCards, will be created in the database, but an exception will be thrown when the object is saved, causing the insertion of the record to fail.
    3. If the table already exists when inserting data

      1. If constrained in wifi.hbm.xml is true, then wifi=session.get(Wifi.class, 1L); delay loading Husband in the Wifi object.

      2. If constrained in husband.hbm.xml is true, then when husband=session.get(Husband.class, 1L); delay loading user in IdCard object.

      3. If constrained in wifi.hbm.xml and husband.hbm.xml is true, this is a combination of the above two, and querying any kind of object will delay loading one of its references

2.1.2, Unique Foreign Key Association

Core Ideas

Foreign key associations, which are originally used in many-to-one configurations, can also be used to represent one-to-one associations when only one restriction is added (using labels to map, specifying more unique s to be true, which limits the multiplicity of one end of the many to be one), which is a special case of many-to-one associations.

For example, a husband has more than one wife, but only one receipt

  1. object model

  2. relational model

  3. Husband class and configuration

    private String hid;
    private String name; 
     <class name="Husband" table="TB_HUSBAND">
           <id name="hid" column="HID">
               <generator class="uuid" />
           </id>
           <property name="name" column="NAME"/>
       </class>
  4. Wife Classes and Configuration

    private String wid;
    
    private String name;
    
    private Husband Husband;
    <class name="Wifi" table="TB_WIFI">
           <id name="wid" column="WID">
               <generator class="uuid"/>
           </id>
           <property name="name" column="NAME"/>
           <many-to-one name="husband" unique="true"/>
    </class>
  5. Test Code

    Core Code Save Object
    Husband husband = new Husband();
    husband.setName("King");
    session.save(husband);
    
    Wifi wifi = new Wifi();
    wifi.setName("empty");
    wifi.setHusband(husband);
    session.save(wifi);
    Query Object
    Wifi wifi = session.find(Wifi.class, "402882215d1de03e015d1de040460001");
    System.out.println(wifi.toString());
    //Output Results
    Wifi{wid='402882215d1de03e015d1de040460001', name='empty', husband=Husband{hid='402882215d1de03e015d1de0403d0000', name='King'}}
  6. Note that because one-to-one primary key Association mappings do not scale well, they become inoperable when our needs change and we want to make them one-to-many, so when we encounter one-to-one associations, we often use unique foreign key associations to solve the problem, but rarely use one-to-one primary key associations.

2.2, Two-way one-to-one

2.2.1. Core Ideas

    Two-way association mapping works the same way as one-way Association mapping. Two-way association mapping does not affect storage but only loading.Therefore, the relationship model of two-way and one-way Association mappings is the same, that is, the table structure of the database is the same

2.2.2, Object Model

2.2.3, Relationship Model

2.2.4, Configuration Information

  1. Husband class and configuration

    private String hid;
    private String name;
    private Wifi wifi;
    <class name="Husband" table="TB_HUSBAND">
     <id name="hid" column="HID">
         <generator class="uuid"/>
     </id>
     <property name="name" column="NAME"/>
          <!--cascade="all" means cascade operation-->
         <!--property-ref="hub" takes the primary key field of the associated entity as the associated field.With property-ref, you can
                By specifying a field other than the primary key of the associated entity as the associated field,
                Note that if you add this field, you will not be able to find WiFi objects through Husband-->
     <one-to-one name="wifi" cascade="all" property-ref="hub" />
    </class>
    <!--cascade="all"-->
    Represents an operation cascading to a child entity
     1.save-update: When you save data with the current end, the other end of the data can be saved together. For example, if cascade="save-update" is set in Student.hbm.xml, then when you save the data, just save Husband, and hibernate will automatically save the Wifi data associated with the other end.
     2.none: Do not cascade (either write or default)
     3.delete: Delete cascade (cannot be performed on more than one end)
     4.all: Indicates that all operations are cascaded
     Matters needing attention
     1.cascade is a cascade operation that allows data to be cascaded at the other end of a data session
     2. In a many-to-one relationship, one end of the many cannot be cascaded as delete, and the other end is generally set as save-update.
     3. In a one-to-many relationship, if one end is set to delete, the many end cannot indicate that the foreign key is empty
  2. Wifi classes and configurations

    private String wid;
    private String name;
    private Husband husband;
       <class name="Wifi" table="TB_WIFI">
           <id name="wid" column="WID">
               <generator class="uuid"/>
           </id>
           <property name="name" column="NAME"/>
           <many-to-one name="husband"  column="HID" not-null="true" unique="true" cascade="all">
           </many-to-one>
       </class>

2.2.6, sample code

  1. Core java code

    Core Code
    Husband husband = new Husband();
    husband.setName("King");
    Wifi wifi = new Wifi();
    wifi.setName("Yui Hatano");
    husband.setWifi(wifi);
    wifi.setHusband(husband);
    session.save(wifi);

  2. Hibernate sql statement

    Hibernate: 
       insert 
       into
           TB_HUSBAND
           (NAME, HID) 
       values
           (?, ?)
    Hibernate: 
       insert 
       into
           TB_WIFI
           (NAME, husband, WID) 
       values
           (?, ?, ?)    
  3. query

    Husband husband = session.get(Husband.class, "402882215d2326e7015d2326e9280000");
    Wifi wifi = session.get(Wifi.class, "402882215d23286e015d2328704e0000");
    String name = wifi.getHub().getName();
    //Notice the memory of the wifi object

  4. Delete operation

    Husband husband = session.get(Husband.class, "402882215d2326e7015d2326e9280000");
    session.delete(husband);
    Hibernate: 
       delete 
       from
           TB_WIFI 
       where
           WID=?
    Hibernate: 
       delete 
       from
           TB_HUSBAND 
       where
           HID=?
    Wifi wifi = session.get(Wifi.class, "402882215d23286e015d2328704e0000");
    session.delete(wifi);
    Hibernate: 
       delete 
       from
           TB_WIFI 
       where
           WID=?
    Hibernate: 
       delete 
       from
           TB_HUSBAND 
       where
           HID=?

2.2.7, Description

The advantage of a unique foreign key association over a primary key association mapping is that in the event that demand changes on a given day and the relationship between the two objects changes from one-to-one to many-to-one, the only constraint on the foreign key is removed.

2.2.8 Foreign Key Association Summary

1. If one party has a foreign key, it can maintain, establish or dissociate the association. It can delete the object at will. If cascade="delete" is set in hbm.xml, it can also delete the associated object.
Unidirectional Association
 2. In the absence of a foreign key, no association relationship can be maintained, no association can be established, and no association can be dissolved.In the deletion process, if there is no foreign key value corresponding to this data, it can be deleted successfully, otherwise an exception will be thrown

2.3, many-to-one and one-to-many

2.3.1. Learning Points

  1. One-to-many one-to-one foreign key Association (XML/Annotation)
  2. One-to-many two-way foreign key Association (XML/Annotation)
  3. Many-to-one one foreign key Association (XML/Annotation)
  4. Lazy and active loading

2.3.2, What is one-way, What is two-way

One-way/Two-way Is there a List orders in the User entity class Is there a User user in the Order entity class
One-way many-to-one nothing
One-way one-to-many Yes nothing
Two-way one-to-many (two-way many-to-one) Yes Yes

2.4, many-to-one one association with foreign keys

Note that many-to-one associations are references by multiple holders.For example, if you go to Jingdong to shop, one Jingdong user can have multiple purchase orders.

2.4.4, Configuration Information

2.4.4.1, Object Model

2.4.4.2, Relationship Model

2.3.4.3, user class and configuration
    private String userId;
    private String username;
    private String password;
  <class name="User" table="TB_USER">
        <id name="userId" column="USER_ID">
            <generator class="uuid"/>
        </id>
        <property name="username" column="USERNAME"/>
        <property name="password" column="PASSWORD"/>
    </class>
2.3.4.3, Order class and configuration
 private String orderId;
 private BigDecimal price;
 private User user;
<class name="Order" table="TB_ORDER">
        <id name="orderId" column="ORDER_ID">
            <generator class="uuid"/>
        </id>
        <property name="price" type="big_decimal" column="PRICE" precision="10" scale="2" />

        <many-to-one name="user" column="USER_ID" not-null="true" cascade="all"/>
    </class>
2.3.4.4, Test Code
  1. Test Save

    1.core Java Code
     User user = new User();
     user.setUsername("zhangwei");
     user.setPassword("123456");
     session.save(user);
    2.Sql Sentence
     Hibernate: 
         insert 
         into
             TB_USER
             (USERNAME, PASSWORD, USER_ID) 
         values
             (?, ?, ?)
    Configuring multiple-to-one associations using <many-to-one>elements
     The name property specifies the property name of the class.
    The column property specifies the name of the library table field,
    The not-null property specifies whether the property is allowed to be empty.
    Lazy property, default lazy load
     The cascade property specifies whether to cascade saves and updates: save-update, delete, all, none

2.5, one-to-many, one-to-one associations with foreign keys

Simply put, it is the opposite of many-to-one before, where the reference of one party was held by many parties and one-to-many association was the reference of one party holding a collection of many parties. Note the difference: here is the collection of holding many parties.

2.5.1, Object Model

2.5.2, Relationship Model

2.5.3, Configuration Information

  1. User Class Configuration

    private String userId;
    private String username;
    private String password;
    private List<Order> orders;
    <class name="User" table="TB_USER">
           <id name="userId" column="USER_ID">
               <generator class="uuid"/>
           </id>
           <property name="username" column="USERNAME"/>
           <property name="password" column="PASSWORD"/>
    
           <list name="orders" table="TB_ORRDER" cascade="all">
            //Database Foreign Key Columns
               <key column="USER_ID"/>
               //Database list index column name
               <index column="ORDER_INDEX"/>
               <one-to-many class="Order"/>
           </list>
       </class>

  2. Order Classes and Configuration

    private String orderId;
    private BigDecimal price;
    <class name="Order" table="TB_ORDER">
           <id name="orderId" column="ORDER_ID">
               <generator class="uuid"/>
           </id>
           <property name="price" type="big_decimal" column="PRICE" precision="10" scale="2" length="10"/>
       </class>

2.5.4, sample code

  1. Table building statement

    Hibernate: 
       create table TB_ORDER (
          ORDER_ID varchar(255) not null,
           PRICE decimal(10,2),
           USER_ID varchar(255),
           ORDER_INDEX integer,
           primary key (ORDER_ID)
       ) engine=InnoDB
    
    Hibernate: 
       create table TB_USER (
          USER_ID varchar(255) not null,
           USERNAME varchar(255),
           PASSWORD varchar(255),
           primary key (USER_ID)
       ) engine=InnoDB
    Hibernate: 
      alter table TB_ORDER 
          add constraint FKfef3qoeyl8ksa381j30wplrj5 
          foreign key (USER_ID) 
          references TB_USER (USER_ID)
  2. Add Object

    #Java Code   
    
     User user = new User();
     user.setUsername("zhangwei");
     user.setPassword("123456");
     List<Order> orders = new ArrayList<>();
     orders.add(new Order(new BigDecimal(50.00)));
     orders.add(new Order(new BigDecimal(50.01)));
     user.setOrders(orders);
     session.save(user);
    
    
    # SQL statement   
    
    Hibernate: 
       insert 
       into
           TB_USER
           (USERNAME, PASSWORD, USER_ID) 
       values
           (?, ?, ?)
    Hibernate: 
       insert 
       into
           TB_ORDER
           (PRICE, ORDER_ID) 
       values
           (?, ?)
    Hibernate: 
       insert 
       into
           TB_ORDER
           (PRICE, ORDER_ID) 
       values
           (?, ?)
    Hibernate: 
       update
           TB_ORDER 
       set
           USER_ID=?,
           ORDER_INDEX=? 
       where
           ORDER_ID=?
    Hibernate: 
       update
           TB_ORDER 
       set
           USER_ID=?,
           ORDER_INDEX=? 
       where
           ORDER_ID=?
  3. Find Object

    Java Code
    User user = session.get(User.class, "402882215d2701fe015d270200b90000");
    //Output Results
      User{userId='402882215d2701fe015d270200b90000', username='zhangwei', password='123456', orders=[Order{orderId='402882215d2701fe015d270200cb0001', price=50.00}, Order{orderId='402882215d2701fe015d270200cb0002', price=50.01}]}
  4. delete object

    #Java Code
    
    User user = session.get(User.class, "402882215d2701fe015d270200b90000");
    session.remove(user);
    
    #Sql statement code
    
    Hibernate: 
       update
           TB_ORDER 
       set
           USER_ID=null,
           ORDER_INDEX=null 
       where
           USER_ID=?
    Hibernate: 
       delete 
       from
           TB_ORDER 
       where
           ORDER_ID=?
    Hibernate: 
       delete 
       from
           TB_ORDER 
       where
           ORDER_ID=?
    Hibernate: 
       delete 
       from
           TB_USER 
       where
           USER_ID=?

2.5, Two-way Foreign Key Association (Important)

Similar to previous one-to-one two-way foreign key associations, they also hold references to each other, so they are also called two-way one-to-many self-associations.A party holds a reference from one party and, conversely, a party holds a collection of parties.

2.5.1, Object Model

2.5.2, Relationship Model

2.5.3, Configuration Information

  1. Category class configuration

    private String cid;
    private String name;
    private Set<CategorySub> subs;
    <class name="Category" table="TB_CATEGORY">
           <id name="cid" column="CID">
               <generator class="uuid"/>
           </id>
           <property name="name" column="NAME" />
           <set name="subs" table="TB_CATEGORY_SUB" cascade="all" inverse="true">
               <key column="CID"/>
               <one-to-many class="CategorySub"/>
           </set>
       </class>
  2. CategorySub class Configuration

       private String sname;
       private String sid;
       private Category category;
    <class name="CategorySub" table="TB_CATEGORY_SUB">
           <id name="sid" column="SID">
               <generator class="uuid"/>
           </id>
           <property name="sname" column="SNAME"/>
           <many-to-one name="category" column="CID" cascade="all"/>
       </class>

2.5.3, sample code

  1. Table building statement

    Hibernate: 
       create table TB_CATEGORY (
          CID varchar(255) not null,
           NAME varchar(255),
           primary key (CID)
       ) engine=InnoDB
    Hibernate: 
       create table TB_CATEGORY_SUB (
          SID varchar(255) not null,
           SNAME varchar(255),
           CID varchar(255),
           primary key (SID)
       ) engine=InnoDB
    Hibernate: 
       alter table TB_CATEGORY_SUB 
          add constraint FKj1mug6ld2o5lpcgo1b2y11l7x 
          foreign key (CID) 
          references TB_CATEGORY (CID)
  2. Save Object

       String[] title = {"Flat", "Computer", "Photography", "Camera", "Entertainment Movie", "Router", "Mobile Accessories", "Peripheral accessories", "Play 3 C"};
    
           Category category = new Category();
           category.setName("Electronic product");
    
           Set<CategorySub> subs = new HashSet<>();
           for (int i = 0; i < 9; i++) {
               CategorySub sub = new CategorySub(title[i]);
               subs.add(sub);
           }
           category.setSubs(subs);
           session.save(category);
    
    
    Hibernate: 
       insert 
       into
           TB_CATEGORY
           (NAME, CID) 
       values
           (?, ?)
    Hibernate: 
       insert 
       into
           TB_CATEGORY_SUB
           (SNAME, CID, SID) 
       values
           (?, ?, ?)
    Hibernate: 
       insert 
       into
           TB_CATEGORY_SUB
           (SNAME, CID, SID) 
       values
           (?, ?, ?)
    Hibernate: 
       insert 
       into
           TB_CATEGORY_SUB
           (SNAME, CID, SID) 
       values
           (?, ?, ?)
    Hibernate: 
       insert 
       into
           TB_CATEGORY_SUB
           (SNAME, CID, SID) 
       values
           (?, ?, ?)
    Hibernate: 
       insert 
       into
           TB_CATEGORY_SUB
           (SNAME, CID, SID) 
       values
           (?, ?, ?)
    ...
    

2.6. Many-to-one and one-to-many summaries:

  1. One-to-many, many-to-one one Association
    1. When many-to-one, EAGER is set by many parties and LAZY is set by one party. That is, if many-to-one and many parties control one party, then many parties set up active loading and one party does not need redundant configuration.
    2. Conversely, in a one-to-many relationship where one party controls many parties, one party sets up lazy loading and many parties do not need redundant configuration, but either way, many parties explicitly add a constructor without parameters.
  2. One-to-many or many-to-one two-way foreign key associations
    1. Used on a collection of one end, adding a foreign key to the opposite table to point to one end.
    2. The foreign key field specified by the tag label at the multiple end must be the same as the specified foreign key field, otherwise the field error will occur.
    3. hibernate maintains one-to-many associations on one end, and hibernate makes redundant update statements. All of us maintain this relationship on more than one end, so we usually add inverse="true" attributes on the set tag to improve system efficiency.
  3. In a many-to-one, one-to-one relationship, Hibernate defaults to inverse=true for many parties, that is, many parties are the accused and one party is inverse=false.

2.6, many-to-many

2.6.1. Core Ideas

One party holds a collection object of the other party
 To achieve a many-to-many relationship, you must have an intermediate table to maintain the relationship between the two parties
CREATE TABLE TB_TEACHER (
SID INT(6),
TID INT(6),
PRIMARY KEY(SID,TID)
)

2.6.2, one-way many-to-many





2.6.3,Two-way many-to-many

2.6.3.1,object model

2.6.3.2,relational model

2.6.3.3,configuration information

  1. Student Configuration of classes

       private Integer sid;
    
       private String sname;
    
       private Set<Teacher> teachers;
<class name="Student" table="TB_STUDENT">
       <id name="sid" column="SID" length="6">
           <generator class="native"/>
       </id>
       <property name="sname" column="SNAME"/>
       <set name="teachers" table="TB_TEACHER_STUDENT" cascade="all">
           <key column="SID"/>
           <many-to-many column="TID" class="Teacher"/>
       </set>
   </class>
  • Configuration of the Teacher class

    private Integer tid;
    private String tname;
    private Set<Student> students;
    <class name="Teacher" table="TB_TEACHER">
           <id name="tid" column="TID" length="6">
               <generator class="native"/>
           </id>
           <property name="tname" column="TNAME"/>
           <set name="students" table="TB_TEACHER_STUDENT" cascade="all">
               <key column="TID"/>
               <many-to-many column="SID" class="Student"/>
           </set>
       </class>
  • 2.6.3.4, Test Code

    1. Table building statement

      Hibernate: 
         create table TB_TEACHER (
            TID integer not null auto_increment,
             TNAME varchar(255),
             primary key (TID)
         ) engine=InnoDB
      Hibernate: 
         create table TB_TEACHER_STUDENT (
            SID integer not null auto_increment,
             TID integer not null,
             primary key (TID, SID)
         ) engine=InnoDB
    2. Add Object

        #java code
        Set<Teacher> teachers = new HashSet<>();
             for (int i = 0; i < 3; i++) {
                 Teacher teacher = new Teacher();
                 teacher.setTname("Teacher" + i);
                 teachers.add(teacher);
             }
             Student s = new Student();
             s.setSname("Xiao Ming");
             s.setTeachers(teachers);
             session.save(s);
      
      Hibernate: 
         insert 
         into
             TB_STUDENT
             (SNAME) 
         values
             (?)
      Hibernate: 
         insert 
         into
             TB_TEACHER
             (TNAME) 
         values
             (?)
      Hibernate: 
         insert 
         into
             TB_TEACHER
             (TNAME) 
         values
             (?)
      Hibernate: 
         insert 
         into
             TB_TEACHER
             (TNAME) 
         values
             (?)
      Hibernate: 
         insert 
         into
             TB_TEACHER_STUDENT
             (SID, TID) 
         values
             (?, ?)
      Hibernate: 
         insert 
         into
             TB_TEACHER_STUDENT
             (SID, TID) 
         values
             (?, ?)
      Hibernate: 
         insert 
         into
             TB_TEACHER_STUDENT
             (SID, TID) 
         values
             (?, ?)
      
    3. Query Object

      Student student = session.get(Student.class, 1);
      System.out.println(student.toString());
      Teacher teacher = session.get(Teacher.class, 1);
      System.out.println(teacher.toString());
    4. delete object

      1. If cascade Whether set by the master or by the defendant all, deleteEqual to anddeleteCascade deletion is sufficient, and records on both ends and in the intermediate table are deleted. This is usually a rare requirement, so if you want this, simply set it toall, deleteIt's easy to clean up relationships and delete records at both ends.
      
      2. You want to delete only one end of the record and the associated information of the intermediate table.This requirement is often common.At this timecascadeThe setting of divide by anddeleteAny cascading constraints related.
      
      2.1. Many-to-Many Master Delete(Intermediate table records can be deleted)
      Student student = session.get(Student.class, tid);
      session.delete(student);
      
      2.2. Many-to-many accused party deletion(Cannot delete intermediate table records)
      
      // If you want to delete both the accused and the Association
      Transaction transaction = session.beginTransaction();
      
      Teacher teacher =session.get(Teacher.class, 1);
      
      Set<Student> cs = teacher.getStudents();
      for (Student student : cs) {
       student.getTeachers().remove(teacher);
      }
      session.delete(teacher);
      transaction.commit();

    2.6.3.5, many-to-many summary

    1. Two entity classes, three tables, and the third table does not require an entity class
    2. When saving and modifying or deleting, you can save or modify or delete data to the intermediate table without manipulating the intermediate table, or one of the two entity classes.
    3. When querying, you do not need to query the intermediate table. You can get the data of the intermediate table by querying one of the other two entity classes and calling the getter method
    4. One table has only two fields that form a union primary key that points to the primary key of the other two tables, and it does not have its own independent auto-incrementing primary key.(The two column s of the child elements in the set tag or bag tag in the map file are the two fields of the third table)
    5. In addition, the many-to-many model can be implemented by two many-to-one, so the concept of many-to-many must be clearly distinguished.For example, users and roles are many-to-many, but they can be implemented in two-to-one or many-to-many ways.The way to distinguish is through the fields of the table.If implemented with many-to-many, then set or bag elements in the map file are followed by a table="intermediate table"

    Topics: Hibernate Session Database xml