hibernate (four) two-way-many mapping between

     Preface

          Inexplicably long a few pox, TM really hurt, and now may be too little movement, every day at the computer, decided this afternoon to spend two hours to go for a run,

          Following the now-many mapping between the previous chapter to explain, to say something about today-many mapping relationship to understand the many, many to many personal feeling is quite easy, you need to reason clearly the relationship between its database Figure, then you won it. Configuration mapping files or always such a dead thing.

                                                --WZY

A small question to answer

       One problem: here, there are many learners will feel confused, because he did not know the use of hibernate is not required to create their own tables, automatic or hibernate, if you need to create your own table, the main foreign key this setting is also set up their own right ? That people feel very confused, now to solve this little doubt (if you know can skip to-many mapping between see explanation below)

       Answer: From the perspective of the actual development, said: certainly create a table, and the table they will import the initial data, then in reverse to generate entity classes, and a variety of mapping between what they need to see what is generated.

          We can also do so in testing and learning phase, to create a good database tables and some initial data, it can not create the good relationship between the various tables in the database and table fields, only you need to manually build the database, that database there is no table of the matter, the key is to have to have this database. If there is no table, then we have to be created by the code table, such as a new entity class, the equivalent of creating a table, under the table if there is no case, you will go directly to the query, the report certainly does not exist error, then the foreign key relationships between each table fields and tables, can help us to complete the degree through hibernate, we write the mapping file and entity classes, it is to create content relationships between tables and tables of. It depends on a configuration property.

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

            value value can into four

                create: represents the start when the first drop, re-create. That every time you start, will be deleted first database table, and then create one. Developers testing the use of more

                create-drop: also represents the creation, but then the system performs before it drop off. Will be closed before each table to delete, such as when used in the creation of

                update: This operation will start when to check whether the schema, and if not do update scheme. Check that is in hibernate and database table field relationship is consistent, inconsistent database is updated

                Verify existing schema is consistent with the configuration of hibernate you start, if not throw an exception, do not update: validate.

 

        Summary: As long as the table exists in our database, we will be able to carry out his operations (transformation of fields in the table, other tables by foreign keys and other joint degree can be completed independently), without the need for us to go to manual operation of the underlying database. So the book is most directly on the operating hibernate code, without concern for how kind database, provided that they have a database table in which they operate is enough.

            

 

    Second problem: the primary key generation strategy in xxx.hbm.xml in, the need to make the underlying database primary key is automatically generated, this need to figure out, can not be confused. When you tangle with a database primary key generation strategy for the primary key in the end that should not be used AUTO_INCREMENT, then you need to sum up the relationship between the two. (I'm a great guy TMD, to help you summarize a)

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

       Primary key generation strategy commonly used on six kinds

        1, increment: hibernate management, automatic key to get the main grow automatically, and the database primary key that you can not set AUTO_INCREMENT up.

        2, identity: the underlying database management, that database needs its own primary key is set to grow automatically (AUTO_INCREMENT), is not set, then you need to manually set up, is not very good.

              Mysql and sql server support for this, but Oracle does not support, that is not supported by the underlying Orable grow automatically, but Oracle has another underlying mechanism that sequence

        3, sequence: the underlying database management, database itself to provide the primary key is how much we do not know specifically how to count

              Oracle will use this, Mysql does not support this, but mysql support identity, that is, let the database to grow automatically, the difference between these two right here, a low-level use AUTO_INCREMENT, a low-level use of this sequence of growth.

        4, native: hibernate does not manage, so how to choose the underlying database primary key generation, that is to say, if it is mysql, it would default identity, that is, we need to set up their own AUTO_INCREMENT, if it is Oracle, then the default sequence, so that which sequence of growth in the underlying database design your own

        5, uuid: that everyone is familiar with, that is what we do not need to set the primary key in the database, each of the primary key will generate a random string of 32

        6, assigned: this is very simple, is that we need to manually set the primary key to their own values, hibernate and database of not taking the initiative to help us set up.

        On the six, is actually very good school, identity and sequence is the need to set ourselves in the database automatically increase or sequence of growth, increment is to help us manage hibernate primary key. The underlying database does not need to write anything, provided that the database needs to support automatic growth, such as Oracle will not take this, native is also a need to set ourselves in the database, but more flexible than the identity and sequence, change the underlying database, you do not need this change, uuid is also very familiar with everyone, assigned this easier, the primary key value is used to write their own thing.  

 

      To this end, the official start of our relationship to-many mapping

 

 

Second, many to many mapping relationship

      Already clear after one to many relationship, then it is much simpler, and many-to-many in fact sub-way and two-way-many, many-but relatively simple way, and use the most is a two-way to-many, and many-to-know two-way, one-way-many is very simple, so we are talking about a two-way direct-many

      There are many examples in life is bidirectional many to many, the most simple and close to our lives,

          The relationship between students and elective 1, students can choose many courses, courses can be selected more than one student,

          2, in Taobao shopping, a commodity that can be selected more than one person, a person can select multiple items

          3, .... many of these many relationships, and student enrollment Take this example to explain the.

 

      To save many relationship, two tables is not enough, we need to add a third table to represent this relationship, look at the following database diagram.

          This figure means that with student_course the middle of the table to save the relationship between the two tables student and course, and student_course is the primary key. But also a foreign key, point cid sid and Course of the student.

          Some people certainly think why use third table, not just use two foreign keys, you point to me, I point you do this, this will expose a big problem, if the learned database should know, such two tables are interrelated, then the relationship between these two tables is fixed in there, which you can not delete delete tables, this small city, when you query a data table will cause an infinite loop, you check I, I checked you in, repeating it. Then the GG.

                      

      Resolve

        Why do we need to set the primary key and two foreign keys:

                student through their own primary key query in the connection table, because it is a composite primary key, so the query to the record there are many, and not only those records on the record of a student of all courses, to get these records, due to the connection table the foreign key of course, it is possible to record the corresponding table course record by c_id, found. Conversely, course through their primary key query to obtain many records in the connection table, the connection table is also a student of a foreign key, the s_id by recording the student can be found in the corresponding record. Therefore, the design is such a table requires the primary key, foreign key and also the city, of these are useful. I can not find a few of the other.

 

 

 

 

        2, the configuration and mapping entity class

    Student persistent classes and Student.hbm.xml

Copy the code
// Student entity class 
public class Student { 
    Private SID Integer; 
    Private String sname; 
    // set with a selected set of a plurality of programs stored 
    Private the Set <Course,> = courseSet new new HashSet <Course,> (); 

  set, GET ... ..   
} 

//Student.hbm.xml 
    <class name = "domain.Student" Table = "Student"> 
        <name ID = "SID" column = "SID"> 
            <-! primary key generation strategy -> 
            <Generator = class "INCREMENT"> </ Generator> 
        </ the above mentioned id> 
        <-! Some general properties -> 
        <property name = "sname"> </ property> 

<-! pivotal place in here. Be sure to refer to figure out two column which is to have a database diagram What does this mean in his head ->

<! <! - This entity class in the connection table of the foreign key name, the course of our analysis above very clearly, why this one? Hibernate let know that the connection point of the present table has a foreign key named entity class of s_id -> <Key column = "s_id"> </ Key> <-! Many to many mapping relationship, mapping classes and classes mapped the connection table foreign key name that means the same as with the above statement is to let hibernate know, this way, to know how to query the hibernate -> <-to-MANY MANY class = "domain.Course" column = " c_id "> </ MANY-to-MANY> </ SET> </ class>
Copy the code

      Course和Course.hbm.xml

Copy the code
// Course entity class 
public class Course, { 
    Private int CID; 
    Private String CNAME; 
    Private the Set <Student> = studentSet new new HashSet <Student> (); 
  ...   
} 

//Course.hbm.xml With the above analysis, the it is simple, content and meaning exactly the same with the above. 
    <class name = "domain.Course" Table = "Course"> 
        <name = ID "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">
      <! - many to many mapping relationship, mapping classes and classes mapped in the connection table name foreign key -> <MANY-to-MANY class = "domain.Student" column = "s_id"> </ many- MANY-to> </ SET> </ class>
Copy the code

 

    3, the test class

Copy the code
// the other is omitted, just write important code. As the newly established relationship, the database does not have any data, then add the initial data. Here there will be a problem. If the comments of this line to open the case, 
reported a org.hibernate.exception.ConstraintViolationException wrong, why is this so? In fact, from our previous analysis of the database design we can know (but that analysis is used as an example query to increase the data with that in much the same),
add a student at the StudentSet course, this process is what is it? Because of StudentSet to operate, it will find the connection table, add a student, it will in the connection table, add a course cid corresponding sid of student records, and then if
you are using student.getCourseSet (). Add (course), then went in the connection table adds a record of exactly the same, this time will certainly be an error ah, because it is the primary key, the same two records, how will interpolated into it. So there will be abnormal constraint violations (violation of primary key constraint) a.
Course = new new Course, Course, (); course.setCname ( "chemical"); Student Student Student new new = (); student.setSname ( "QQQ"); . Course.getStudentSet () the Add (Student); // student.getCourseSet () .add (Course); Session.save (Course); Session.save (Student);
Copy the code

 

     4, the effect of FIG.

               

V. Summary  

       After the two-way-many will find it simple to understand, but in the beginning to learn, feel around inside it, you must know what each step is important to understand why the connection table needs to be set like that. You will understand easily learned this bi-many mapping relationship, you have to realize about their own hands, which hides a lot of BUG, ​​needs its own to resolve. If you do not Write it, then you understand, a few days or rely on grabbing other people's code, rather than write himself. 

Guess you like

Origin www.cnblogs.com/Jeely/p/11226995.html