cool hit counter SSH framework journey - hibernate (3)_Intefrankly

SSH framework journey - hibernate (3)


hibernate

1.table relationship


1.1 Data Table Basics

Let's start by reviewing the basics of databases.

  • Primary Key: A field or combination of fields in a data table that uniquely identifies a record is called a primary key. The primary key of each record of a data table is unique and non-repeating. A primary key that uniquely identifies a record is only one role of a primary key; another role of a primary key is to associate with other records and the table that holds the data, at which point a primary key becomes a foreign key to another table.
  • external key: A field where a data table is associated with other data tables is called because of is a foreign key。 Pass a foreign key field, A data table can know all the data of another data table associated with it, A data table can have more than one foreign key field, That is, a single data table can be associated with multiple data tables。 A data table that has a foreign key can be called because of base table, The table associated with it is called because of information sheet。
  • index: A primary key in a data table uniquely identifies a record, And the index has this function as well, do because of Each data value of the indexed field must be unique in this data table。 for example: A person's ID number can be used as because of Index fields of a data table。

Primary foreign key relationship: the foreign key must be the primary key of another table.

1.2 Three table relationships

  • 1.2.1 One-to-One Table Relationships

a table (listing information) A A record in a table can only be linked to the B of a record, vice versa。 Tables of such relationships are not common, reason because of Since data can be stored in two tables, It is also possible to use a table to store。 The one-to-one table relationship is used for: 1.Splitting a table with many columns 2.Isolation of a part of the table due to security concerns 3.Storing some temporary data that can be easily deleted, deleting these tables is deleting that data 4.Store information that is applied to only a subset of the main table

As an example, by law, a man has only one wife and a woman has only one husband. If you put the men in one table and the women in another, then a record in the men's table corresponding to a record in the women's table can only be unique, but of course this is more likely to be the case where they are stored in one table.

The principles of table construction are.

  1. The unique foreign key corresponds, assuming that in a one-to-one, either side is many, then create a foreign key on the many side pointing to the primary key of the one side, and then set the foreign key to be unique. For example, a man can have many women, but legally only one wife at a time. 2.Primary key correspondence: the primary key of one party is used as the primary key of the other party.
  • 1.2.2 One-to-many table relationships

a table (listing information) A One of the records in the table B Multiple lines can be matched in, But in the table B A record in the table A There can only be one matching line in, Here's the table A call oneself because of Party to the relationship, a table (listing information) B call oneself because of Multiple parties in the relationship。 One-to-many table relationships are more common, For example, in the student table, A student belongs in a class, And in the class table, A class can have many students, This relationship is known as because of One-to-many relationships。 At this point the student table has a field for because of Foreign keys for class tables, Students are the side with more, Classes are the side of one, Create a foreign key on the side of the multi, Primary key that points to the side of one。

The principles of table construction are. Create a foreign key on the side of the many to point to the primary key on the side of the one.

  • 1.2.3 Many-to-many table relationships

a table (listing information) A A record in the table B Matching multiple lines in, vice versa。 for example A student can take more than one course, One course also has many students choosing, This relationship is a many-to-many relationship, Many-to-many relationships have to be maintained with the help of a third table between the two parties, The relationships between students and courses are stored in a relationship table, The primary key field of this relational table is a combination of the primary key of the student table and the primary key of the course table。

The principles of table construction are. Create an intermediate table with at least two fields in the intermediate table as foreign keys to point to the primary keys of each of the two pairs of geodetic parties.

2.one-to-many mapping


2.1 Basic code

The following is illustrated by examples from students and classes

  • Student entity category

The properties of the student entity class are to be added to the objects of the class entity class.

package cc.wenshixin.entity;

public class Student {

    private Integer id; //  Student School Number
    private String name; //  Student Name
    private String sex; //  Gender of student

    private Banji banji; //  A student belongs to only one class

    public Student(String name, String sex) {
        this.name = name;
        this.sex = sex;
    }

    public Student() {

    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Banji getBanji() {
        return banji;
    }

    public void setBanji(Banji banji) {
        this.banji = banji;
    }
}
  • Class entity category

The students in the class are saved with the set collection.

package cc.wenshixin.entity;

import java.util.HashSet;
import java.util.Set;

public class Banji {

    private Integer id; // Class Number
    private String name; // Class name
    
    private Set<Student> setStudent = new HashSet<Student>(); // A class with multiple students

    public Banji() {

    }

    public Banji(String name) {
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set<Student> getSetStudent() {
        return setStudent;
    }

    public void setSetStudent(Set<Student> setStudent) {
        this.setStudent = setStudent;
    }
}
  • Configuring the entity class mapping file

Mapping file for the student entity class <many-to-one name="banji" class="cc.wenshixin.entity.Banji" column="banji"></many-to-one> among others name is the name of the class attribute of the entity class.class because of name the full pathname of the attribute value class.column is the name of the foreign key field in the student table.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="cc.wenshixin.entity.Student" table="student">
        <id name="id" type="java.lang.Integer" column="sid">
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String" column="sname">
        </property>
        <property name="sex" type="java.lang.String" column="sex">
        </property>
        <many-to-one name="banji" class="cc.wenshixin.entity.Banji" column="banji">
        </many-to-one>
    </class>
</hibernate-mapping>

Class entity class mapping file

    <set name="setStudent" table="student">
        <key column="banji">
        </key>
        <one-to-many class="cc.wenshixin.entity.Student" />
    </set>

name attribute is the name of the set collection in the class entity class, thetable because ofStudent entity category Name of the data table created, Can be omitted, reason because of hibernate is by default a two-way maintenance foreign key, That is, foreign keys should be configured on both one and many sides,key tagged column is the foreign key name in the student entity class data table, to be consistentone-to-many Tagged in. class is the full pathname of the student entity class.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="cc.wenshixin.entity.Banji" table="banji">
        <id name="id" type="java.lang.Integer" column="bid">
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String" column="bname">
        </property>
        <set name="setStudent" table="student" inverse="true" cascade="save-update, delete">
            <key column="banji">
            </key>
            <one-to-many class="cc.wenshixin.entity.Student" />
        </set>
    </class>
</hibernate-mapping>

Note: To load the mapping file for the entity class in the core configuration file.

hibernate Tool Classes

Facilitates better use of hibernate in test code.

package cc.wenshixin.utility;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtility {
    private static Configuration cfg = null;
    private static SessionFactory sessionFactory = null;
    
    static{
        cfg = new Configuration().configure();
        sessionFactory = cfg.buildSessionFactory();
    }
    
    /* Provide methods to returnsessionFactory*/
    public static SessionFactory getSessionFactory()
    {
        return sessionFactory;
    }
}

2.2 Operation of one-to-many relationships

  • General Preservation

The downside is that it requires two saves, which is not very efficient.

    @Test
     // General Preservation
    public void testSave1()
    {
        SessionFactory sessionFactory = HibernateUtility.getSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        try {
            
             //Add students and classes
            Banji banji = new Banji(" Accounting Class 2");
            Student student = new Student(" Simon", " male");
            
             Add students to the // class object
            banji.getSetStudent().add(student);
             //Setting the class in the /Student object
            student.setBanji(banji);
            
             //Save classes and students
            session.save(banji);
            session.save(student);
            
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally{
            session.close();
        }
    }
  • One-to-many cascade preservation

Save one side, and the multiple parties associated with it are automatically saved with a directional save operation.

It needs to be added to the set tag in the mapping file of one side cascade="save-update" , so that you can just write save class and the students added to the class will be saved automatically.

    @Test
     // One-to-many cascade preservation write-ups
    public void testSave2()
    {
        SessionFactory sessionFactory = HibernateUtility.getSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        try {
            
             //Add students and classes
            Banji banji = new Banji(" Accounting class 8");
            Student student = new Student(" small red", " women");
            
            banji.getSetStudent().add(student);

             // Only students need to be saved
            session.save(banji);
            
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally{
            session.close();
        }
    }
  • General deletion

Only the students in a class are deleted, not the class.

    @Test
    // General deletion
    public void testDelete1()
    {
        SessionFactory sessionFactory = HibernateUtility.getSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        try{
            // Perform deletion
            Banji banji = session.get(Banji.class, 15);
            Student student = session.get(Student.class, 11);
            
            banji.getSetStudent().remove(student);
            session.delete(student);
        
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }   finally {
            session.close();
        }
    }
  • One-to-many cascade deletion

When deleting a class, All students in this class are to be deleted as well, But because of the foreign key constraint, Classes cannot be deleted directly, and remove the student, (located) athibernate If you delete the class directly in the, Then the foreign key value of the student associated with it will be changed because of null, If you want to delete both the class and the student, Then it needs to be in Class entity category in the mapping file of thekey Add inside the label upper cascade="save-update, delete" In fact, hibernate's delete operation also sets the foreign key to null to sever the association and then deletes it.

    @Test
    // one-to-many cascade deletion
    public void testDelete2()
    {
        SessionFactory sessionFactory = HibernateUtility.getSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        try{
        // Perform deletion
            Banji banji = session.get(Banji.class, 12);
            session.delete(banji);
        
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }   finally {
            session.close();
        }
    }
  • one-to-many Cascade Modification

Because hibernate maintains foreign keys in both directions, it is necessary to maintain foreign keys in the data tables of one party and multiple parties, and modifying the foreign key value of any party will require the other party to modify it as well, which will cause efficiency problems. set Add to the tag inverse="true" configuration, the default hibernate is not to drop foreign key maintenance, that is, false.

    @Test
    // one-to-many Cascade Modification
    public void testUpdate()
    {
        SessionFactory sessionFactory = HibernateUtility.getSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction tx= session.beginTransaction();
        
        try{
            // execute Modify operation
            Banji banji = session.get(Banji.class, 14);
            Student student = session.get(Student.class, 10);
            banji.getSetStudent().add(student);
            student.setBanji(banji);
            
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
        }
    }

3.many-to-many mapping


3.1 Basic code

The following is illustrated by examples of students and courses

  • Student entity category

Student entity category to be added to the properties of Course entity category of the collection object。

package cc.wenshixin.entity;

import java.util.HashSet;
import java.util.Set;

public class Student {
    private Integer id; //  Student School Number
    private String name; //  Student Name
    private String sex; //  Gender of student

    private Set<Course> setCourses = new HashSet<Course>(); //  A student can take more than one course

    public Set<Course> getSetCourses() {
        return setCourses;
    }

    public void setSetCourses(Set<Course> setCourses) {
        this.setCourses = setCourses;
    }

    public Student(String name, String sex) {
        this.name = name;
        this.sex = sex;
    }

    public Student() {

    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}
  • Course entity category

Course entity category to be added to the properties ofStudent entity category of the collection object。

package cc.wenshixin.entity;

import java.util.HashSet;
import java.util.Set;

public class Course {
    
    private Integer id; // Course Number
    private String name; // Course Name
    
    private Set<Student> setStudent = new HashSet<Student>(); // Multiple student options for one course

    public Course() {

    }

    public Course(String name) {
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set<Student> getSetStudent() {
        return setStudent;
    }

    public void setSetStudent(Set<Student> setStudent) {
        this.setStudent = setStudent;
    }
    
}
  • Configuring the entity class mapping file

Mapping file for the student entity class

set Tagged in. table for the name of the third table.key Tagged in. column The value of the property because of The name of a field in the third table,many-to-many Tagged in. class because of Full pathname of the entity class for another party,column The value of the attribute is the field name of another entity class in the third table.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="cc.wenshixin.entity.Student" table="student">
        <id name="id" type="java.lang.Integer" column="sid">
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String" column="sname">
        </property>
        <property name="sex" type="java.lang.String" column="sex">
        </property>
        <set name="setCourses" table="student_course">
            <key column="stutentid">
            </key>
            <many-to-many class="cc.wenshixin.entity.Course" column="courseid"/>
        </set>
    </class>
</hibernate-mapping>

Course entity category The mapping file for the

Same explanation of the mapping configuration as the entity class.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="cc.wenshixin.entity.Course" table="course">
        <id name="id" type="java.lang.Integer" column="cid">
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String" column="cname">
        </property>
        <set name="setStudent" table="student_course">
            <key column="courseid">
            </key>
            <many-to-many class="cc.wenshixin.entity.Student" column="stutentid"/>
        </set>
    </class>
</hibernate-mapping>

Corresponding mapping configuration relationship diagram

Mapping Configuration Relationships Correspondence Diagram

3.2 Operation of many-to-many relationships

  • General Preservation

The statements are wordy.

    @Test
     // General Preservation
    public void testSave1()
    {
        SessionFactory sessionFactory = HibernateUtility.getSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        
        try{
             // Perform a save operation
            Student s1 = new Student(" Simon", " male");
            Student s2 = new Student(" small red", " women");
            
            Course c1 = new Course("php Dynamic Web Development");
            Course c2 = new Course("java computer programming");
            Course c3 = new Course(" design pattern");
            
             // Students select courses, courses are selected
            s1.getSetCourses().add(c1);
            s1.getSetCourses().add(c2);
            s2.getSetCourses().add(c2);
            s2.getSetCourses().add(c3);
            
            session.save(s1);
            session.save(s2);
            session.save(c1);
            session.save(c2);
            session.save(c3);
            
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
        }
    }
  • Multi-to-multiple cascade preservation

Mapping the configured in the student entity class set Add to the tag cascade="save-update" The only thing you need to do is to save the student, and the course selected by the student will be saved automatically.

    @Test
     / Cascade preservation
    public void testSave2()
    {
        SessionFactory sessionFactory = HibernateUtility.getSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        
        try{
             // Perform a save operation
            Student s1 = new Student(" Simon", " male");
            Student s2 = new Student(" small red", " women");
            
            Course c1 = new Course("php Dynamic Web Development");
            Course c2 = new Course("java computer programming");
            Course c3 = new Course(" design pattern");
            
             // Students select courses, courses are selected
            s1.getSetCourses().add(c1);
            s1.getSetCourses().add(c2);
            s2.getSetCourses().add(c2);
            s2.getSetCourses().add(c3);
            
            session.save(s1);
            session.save(s2);

            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
        }
    }
  • General deletion

Deletes data from only one multiple party, without affecting another.

    @Test
    // General deletion
    public void testDelete1()
    {
        SessionFactory sessionFactory = HibernateUtility.getSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        
        try{
            // delete operation
            Student s1 = session.get(Student.class, 1);
            session.delete(s1);
            
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
        }
    }
  • Multi-to-multiple cascade deletion

Deleting a multiparty while affecting the data of another multiparty requires a multiparty in the configuration file set Add inside the label cascade="save-update, delete"

    @Test
    // cascade deletion
    public void testDelete2()
    {
        SessionFactory sessionFactory = HibernateUtility.getSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        
        try{
            // delete operation
            Student s1 = session.get(Student.class, 1);
            session.delete(s1);
            
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
        }
    }
  • many-to-many Cascade Modification

Does not change the records of two multi-party data tables, Instead, it maintains the relationship records in the third table, lower Modify operation Includes adding a relationship record and deleting a relationship record。

    @Test
    // Cascade Modification
    public void testUpdate()
    {
        SessionFactory sessionFactory = HibernateUtility.getSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        
        try{
            // Modify operation
            Student s1 = session.get(Student.class, 1);
            Course c3 = session.get(Course.class, 3);
            // Letting students choose their courses3
            s1.getSetCourses().add(c3);
            
            Student s2 = session.get(Student.class, 2);
            Course c1 = session.get(Course.class, 1);
            //Keeping students from taking courses1
            s2.getSetCourses().remove(c1);
            
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            session.close();
        }
    }

Recommended>>
1、cf914FSubstringsinaStringbitset string match
2、From HTTP09 to HTTP2 An article on the historical evolution and design thinking of the HTTP protocol
3、Masayoshi Sons giant fund has started investing first list BrainCorp Plenty and more
4、go finds a string from a known list
5、Vuejs front and back end isomorphic solution of preparation code optimization

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号