Hibernate Learning Series-----(7) Hibernate list collection of actions for set properties

Source: Internet
Author: User
Tags relational database table

Today to write the content is not much, this is going to hibernate to set the operation of the content directly boils down to an article, but think about, or separate write better, after all, the front has been released, nonsense not to say, start it!

Still create a new Studentlist.java entity class, the other properties are unchanged, just change the hobby property from the Set collection type to the list collection type, or paste the code out, I hope not wearies

 Packagecom.joe.entity;Importjava.util.List; Public classStudentlist {Private intID; PrivateString name; Private intAge ; PrivateList<string>Hobby; /*** No parameter constructor*/     Publicstudentlist () {} Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicList<string>Gethobby () {returnHobby; }     Public voidSethobby (list<string>Hobby) {         This. Hobby =Hobby; }    }

Next, we all know, is to configure the StudentList.hbm.xml object relationship mapping file, first say <list> tag bar,<list> Elements are used to map properties of the Java.util.List type, and commonly used properties and child elements are:

    1. Name property
    2. Table Property
    3. <key> child elements
    4. <list-index> child elements
    5. <element> child elements

Then put the code:

<?XML version= "1.0" encoding= "UTF-8"?><!DOCTYPE hibernate-mapping SYSTEM "Http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping>    <!--a class tag corresponds to an entity class, the name attribute specifies the entity class name, and the table property specifies the associated database table -    <classname= "Com.joe.entity.StudentList"Table= "Stu_list_tab">        <!--PRIMARY Key -        <IDname= "id"column= "stu_id">            <!--the policy of providing ID increment native will be judged by the database itself -            <Generatorclass= "Native"></Generator>        </ID>        <!--other properties, name corresponding to the attribute of the entity class, column corresponding to the relational database table -        < Propertyname= "Name"column= "Stu_name"></ Property>        < Propertyname= "Age"column= "Stu_age"></ Property>                <Listname= "Hobby"Table= "Hobby_list_tab">            <Keycolumn= "student_id"></Key>            <List-indexcolumn= "position"></List-index>            <elementtype= "string"column= "Hobby"></element>        </List>            </class></hibernate-mapping>

To read the list tag.,<key> child elements and <element> sub-elements are not much to say, mainly <list-index> sub-elements, I checked the information, you can also use <INDEX> Because the list collection is an ordered, repeatable collection, use <index-index column= "position"/></list-index> ( or using <index column= "position" ></index>) to indicate their order. (Position is an additional field in the Hobby_list_tab table), so you need to maintain the position field when you insert the update, or the index is set incorrectly, and the data you take out will appear empty.

If the <list> tag is configured with the inverse= "true" property, the index of the list is not actively assigned, the index column produces a null value, and if the index column database setting can be empty, the data can be saved normally. When you use Hibernate to query the object data, it throws a null index column for collection: This type of error. That is, the list that is configured with inverse is true, and you need to maintain the index columns manually. It feels quite complicated and a bit stirred.

Of course, you can also use <bag> (combined with the list and set) tags to configure the list collection properties, a collection that can be repeated without order, and is provided by Hibernate. Hibernate uses the JDK's list simulation bag. Its configuration is basically the same as Hibernate mapping list. This is not discussed here, after all, it is directed at the list.

Still build a Studentlisttest.java test class, write a method to create the table structure first:

@Test public    void CreateTable () {        Configuration cfg = new Configuration (). Configure ();        Schemaexport se = new Schemaexport (CFG);        Se.create (True, true);    }

Execute the method to see the results of hibernate execution:

When creating the Hobby_list_tab table, you can see that the position field configuration is not a null property, which also reflects the previous list label configuration, more information can be found in their official documentation, here is a quick channel: click here

Test of the Add () method:
/*** methods to add*/@Test Public voidAdd () {Transaction tx=NULL; Session Session=NULL; Try{Session=hibernateutils.getsession (); TX=session.begintransaction (); Studentlist Student=Newstudentlist (); Student.setname ("Zhangsan"); Student.setage (20); List<String> list=NewArraylist<string>(); List.add ("Basketball"); List.add ("Swimming");                        Student.sethobby (list);                                    Session.save (student);        Tx.commit (); }Catch(Hibernateexception He) {if(tx!=NULL) {tx.rollback ();        } he.printstacktrace (); }finally{hibernateutils.closesession (session); }    }

To perform this method, look at the output information of the console:

Only one thing to explain is that I do not have a position skin in the program, that position field has a value, if so, why value? Open the MySQL database and you'll know it at once:

Ay, there is a value, this is a mechanism provided by hibernate, it is automatically maintained as long as you are configured correctly. One more question to keep in mind is why is it starting from 0 instead of other values? This is associated with our list collection, where the bottom of the list is a dynamic array, so when you add an element, the subscript starts at 0.

Test of the FindAll () method:
@Test Public voidFindAll () {Transaction tx=NULL; Session Session=NULL; Try{Session=hibernateutils.getsession (); TX=session.begintransaction (); Studentlist Stu= (studentlist) session.get (studentlist.class, 1); System.out.println (Stu.getid ()+stu.getname () +stu.getage ());        Tx.commit (); }Catch(Hibernateexception He) {if(tx!=NULL) {tx.rollback ();        } he.printstacktrace (); }finally{hibernateutils.closesession (session); }    }

Similar to the previous test, only access the basic properties, I think hibernate execution action Everyone knows, there will only be a SELECT statement, not to access the Hobby_list_tab table, or paste:

Next, add the code that accesses the Hobby property:

// Accessing the Hobby property            List<string> hobby=stu.gethobby ();              for (String str:hobby) {                System.out.println (str);            }

Believe the result everyone still know, still stickers:

In fact, I feel this article and the previous article a little repetition, but not bored to death, after all, knowledge is a step-by-step learning, the next one or two, the rhythm is probably still so, you crossing, do not think I wordy yo.

Hibernate Learning Series-----(7) Hibernate list collection of actions for set properties

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.