Reprinted---Hibernate learning four

1. Answers to small questions

       Question 1: At this point, many learners will be confused, because they do not know whether to use hibernate to create tables by themselves, or hibernate is fully automatic, if you need to create tables by yourself, is the setting of primary and foreign keys also set by yourself? ? This is very confusing, let's solve this little question now (if you know it, you can skip it and see the explanation of the many-to-many mapping relationship below)

       Answer: From the point of view of actual development: it must be created first, and the initial data will be imported into the table, and then the entity class will be generated in reverse, and the various mapping relationships will be generated according to what you need.

          This can also be done in our testing and learning stages. First, create the database and table and some initialization data. You can also do not need to create various table relationships and table fields in the database. You only need to manually build the database, that is to say, the database It doesn't matter whether there is a table or not, the key is that there must be this database. If there is no table, then we have to create a table through code. For example, a new entity class is equivalent to creating a table. If there is no table, you can directly query, and it will definitely report that there is no table. Error, then the foreign key relationship between the fields in each table and the table can be completed by hibernate for us. We write the mapping file and entity class to create the relationship between the tables and the content in the table. It depends on a configuration property.

            <prop key="hibernate.hbm2ddl.auto">value</prop>

            value can be four

                create: means drop first, then create when starting. That is to say, each time it is started, the table in the database will be deleted first, and then one will be created. Developers use more testing

                create-drop: also means create, but execute drop before the system shuts down. The table is deleted before each shutdown, and it is created when it is used.

                update: When this operation is started, it will check whether the schema is consistent. If it is inconsistent, the schema will be updated. It is to check whether the relationship between the fields in hibernate and the database table is consistent, and if they are inconsistent, the database will be updated.

                validate: Validate whether the existing schema is consistent with the hibernate you configured at startup. If it is inconsistent, an exception will be thrown and no update will be made.

 

        Summary: As long as there is a table in our database, we can operate it (modify the fields in the table, and combine other tables through foreign keys, etc.), without requiring us to manually operate the underlying database. Therefore, in most books, the code for operating hibernate is directly operated, and they do not care about the database. Their premise is that there are tables in the database that they operate on.

            

 

    Question 2: Whether the primary key generation strategy in xxx.hbm.xml needs to be automatically generated for the underlying primary key of the database, this needs to be clarified and cannot be confused. When you are struggling with the primary key generation strategy and whether AUTO_INCREMENT should be used for the database primary key, then you need to summarize the relationship between the two. (I am a good person TMD, I will summarize it for you)

            <id name="id" column="id">
                  <!-- 主键生成策略 -->
                  <generator class="increment"></generator>
                </id>

       There are only six commonly used primary key generation strategies,

        1. Increment: Hibernate manages, automatically allows the primary key to grow automatically, and the primary key in the database does not need to set AUTO_INCREMENT.

        2. identity: The underlying database management, that is to say, the database needs to set the automatic growth of the primary key (AUTO_INCREMENT) by itself. If it is not set, it needs to be set manually by itself, which is not very good.

              Mysql and sql server support this, but Oracle does not, that is to say, Orable does not support automatic growth at the bottom, but Oracle has another underlying mechanism, which is sequence

        3. sequence: the underlying database management, how much the database itself provides this primary key, we don’t know how to calculate it

              Oracle uses this, Mysql does not support this, but mysql supports identity, that is, allows the database to grow automatically. The difference between the two is here. One bottom layer uses AUTO_INCREMENT, and the other bottom layer uses this serialization growth.

        4, native: hibernate does not manage, let the database bottom layer choose how to generate the primary key, that is to say, if it is mysql, then identity is used by default, that is, we need to set AUTO_INCREMENT ourselves, if it is Oracle, then sequence is used by default, let Which serialization growth is designed at the bottom of the database itself

        5. uuid: This is familiar to everyone, that is, we do not need to set anything on the primary key in the database, each time a random 32-bit string will be generated for the primary key

        6. Assigned: This is very simple, that is, we need to manually set the value for the primary key, and hibernate and the database do not take the initiative to help us set it.

        These six are actually very easy to learn. Identity and sequence require us to set up automatic growth or serialized growth in the database. Increment means that hibernate helps us manage the primary key. There is no need to write anything at the bottom of the database, provided that the database needs to support automatic growth. For example, Oracle cannot use this. Native also needs to be set in the database by ourselves, but it is more flexible than identity and sequence. Changing the underlying database is not required. Change, uuid is also very familiar to everyone, assigned is simpler, it is used to write the primary key value by yourself.  

 

      This is the end, officially start our many-to-many mapping relationship

 

 

2. Many-to-many mapping relationship

      After the one-to-many relationship is clear, it is much simpler. Many-to-many is actually divided into one-way many-to-many and two-way many-to-many, but one-way many-to-many is relatively simple, and the most used one is two-way. Many-to-many, know that two-way many-to-many, one-way many-to-many is very simple, so we directly talk about two-way many-to-many

      There are many examples in life that are two-way many-to-many, the simplest and closest to our lives,

          1. The relationship between students and course selection is now complete. Students can choose multiple courses, and courses can be selected by multiple students.

          2. When shopping on Taobao, one product can be selected by multiple people, and one person can choose multiple products

          3. ... Many of these many-to-many relationships, let's take the example of students and course selection to explain.

 

      To save a many-to-many relationship, two tables are not enough, and a third table needs to be added to represent this relationship. See the database relationship diagram below.

          This figure means that the intermediate table student_course is used to save the relationship between the two tables, student and course, and student_course is the joint primary key. It is also a foreign key, pointing to the sid of the student and the cid of the Course.

          Some people will definitely think why use the third table instead of directly using two foreign keys, you point to me, I point to you like this, this will expose a big problem, if you have studied database, you should know, Such two tables are related to each other, then the relationship between the two tables is fixed there. You cannot delete which table you delete. This urban trivial matter, when you query the data in a table, will cause an infinite loop, you checked Me, I'm checking you again, and it goes on and on. That's GG.

                      

      Parse

        Why do you need to set a joint primary key and two foreign keys:

                Students query in the join table through their own primary key. Because it is a composite primary key, there are many records queried, not unique. These records record all the courses of a student. After getting these records, due to the join table There is a foreign key in course, so the corresponding record in the course table can be found through the c_id in the record. Conversely, course uses its own primary key to query the connection table to obtain many records. Since the connection table also has the foreign key of the student, the corresponding record in the student can also be found through the s_id in the record. So, the design of the table is such that you need a joint primary key, and also urban foreign keys, these degrees are useful. Without one, you can't find each other.

 

 

 

 

        2. Entity class and mapping configuration

    Student persistence class and Student.hbm.xml

copy code

//Student entity class
public class Student {
    private Integer sid;
    private String sname;
    //Use the set collection to save the selected courses
    private Set<Course> courseSet = new HashSet<Course>();

  set、get.....  

//Student.hbm.xml
    <class name="domain.Student" table="student">
        <id name="sid" column="sid">
            <!-- Primary key generation strategy -->
            <generator class="increment"></generator>
        </id>
        <!-- some general properties -->
        <property name="sname"></property>

<!-- This is where the key lies. Be sure to figure out what the two columns mean, and which database relationship diagram should be in your head -->

<!--To query all courses, you need to pass the connection table, so declare the name of the connection table-->
    <set name="courseSet" table="student_course">
    <!-- The foreign key name of this entity class in the join table, the process we analyzed above is very clear, why do we need this? Let hibernate know that there is a foreign key named s_id in the join table that points to this entity class -->
        <key column="s_id"></key>
        <!-- Many-to-many mapping relationship, the meaning of the foreign key name of the mapping class and its mapping class in the join table is the same as the above, and it is also declared to let hibernate know, so that hibernate knows how to query -- >
        <many-to-many class="domain.Course" column="c_id"></many-to-many>
    </set>
    </class>

copy code

      Course和Course.hbm.xml

copy code

//Course entity class
public class Course {
    private int cid;
    private String cname;
    private Set<Student> studentSet = new HashSet<Student>();
  ...  

//Course.hbm.xml With the above analysis, this is simple, and the content and meaning are exactly the same as above.
    <class name="domain.Course" table="course">
        <id name="cid" column="cid">
            <!-- Primary key generation strategy -->
            <generator class="increment"></generator>
        </id>
        <!-- some general properties -->
        <property name="cname"></property>
        <set name="studentSet" table="student_course">
            <!-- The name of the foreign key of this class in the join table, -->
            <key column="c_id"></key>
      <!--Many-to-many mapping relationship, the foreign key name of the mapping class and its mapping class in the join table-->
            <many-to-many class="domain.Student" column="s_id"></many-to-many>
        </set>
    </class>

copy code

 

    3. Test class

copy code

//Others are omitted, and only important code is written. Due to the newly established relationship, there is no data in the database yet, so the initial data is added. A problem arises here. If you let go of the commented line,
Report an org.hibernate.exception.ConstraintViolationException error, why is this happening? In fact, we can know from our analysis of the database design diagram above (only that analysis uses query as an example, and adding data is similar to that process),
What is the process of adding a student to the StudentSet of the course? Because you want to operate on StudentSet, you will find the connection table and add a student, then in the connection table, add a record with the cid of the course corresponding to the sid of the student, and then if
If you are using student.getCourseSet().add(course), and add an identical record to the connection table, you will definitely get an error at this time, because it is a joint primary key, and the two records are the same, how can they be inserted? . So there will be a constraint violation exception (primary key constraint violation).

    
        Course course = new Course();
        course.setCname("化学");
        
        Student student = new Student();
        student.setSname("qqq");

        course.getStudentSet().add(student);
//        student.getCourseSet().add(course);
        
        
        session.save(course);
        session.save(student);

copy code

 

     4. Rendering

               

V. Summary  

       After understanding two-way many-to-many, you will find that it is very simple, but when you start learning, you will feel that it is very confusing, so you must know what each step is, and it is important to understand why the connection table needs to be set like that. After understanding it, you will easily learn this two-way many-to-many mapping relationship. You must implement it yourself. There are many bugs hidden in it and you need to solve it yourself. If you don't write it by hand, then you understand it. After a few days, you still have to rely on other people's code instead of writing it yourself. 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325079166&siteId=291194637