Hibernate Learning Series-----(6) Hibernate set set of actions for set properties

Source: Internet
Author: User
Tags relational database table set set

Say a piece of crap first, this intends to summarize the knowledge learned every day as a blog, but why didn't you write it yesterday? No study? No, why is that? Fun, right, the classmate said right, frankly yesterday felt not very comfortable, we all know, this is actually for their own lazy excuses, OK, nonsense first chatter here, the following into the topic.

Let's talk about concepts first.

In a persisted class, sometimes the object property of a value type is used, an object of the so-called value type, which means that its corresponding class has no object identifier attribute, which is what we said earlier, and can only be used as a property of a persisted class. If a collection of value types is persisted in a class, then an additional database table is required to hold the data for the collection of value types, which is called the collection table.

One thing to note is that hibernate3.0 started to support most of the important JDK aggregation interface mappings later, and of course, the current development is basically using a version of 3.0 later,

To do this, we create a new entity class in the project, I name Studentset.java, give it a few attributes, which is a special attribute is the Hoppy property, which is a set set type, represented as a multi-relationship:

 Packagecom.joe.entity;ImportJava.util.Set;/** *  * @authorJoe * studentset java Bean*/ Public classStudentset {Private intID; PrivateString name; Private intAge ; PrivateSet<string>Hobby; /*** Non-parametric constructors*/     PublicStudentset () {} 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 ; }     PublicSet<string>Gethobby () {returnHobby; }     Public voidSethobby (set<string>Hobby) {         This. Hobby =Hobby; }}

When configuring the Entity care Mapping file, pay special attention to the configuration of the set label:<set> element is used to map properties of the Java.util.Set type, commonly used properties and child elements are:

    1. Name property: The Set collection property in the corresponding entity class
    2. Table property: Tables structure for the current set collection
    3. <key> child elements: foreign key columns of the table structure corresponding to the set set
    4. <element> Sub-elements: Save the data stored in the collection
<?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.StudentSet"Table= "Stu_set_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>                <Setname= "Hobby"Table= "Hobby_tab">            <Keycolumn= "student_id"></Key>            <elementtype= "string"column= "Hobby"></element>        </Set>            </class></hibernate-mapping>

Where key is the foreign key of the Hobby_tab, the element tag is the field that maps to the collection in the database, and it is important to set the Type property for the element tag, otherwise it throws an exception. After you've written it, don't forget to add the mapping to the Hibernate.cfg.xml file, next, create a new Studentsettest.java test class in the test package under the Tests folder, and under that class, add the following method first:

@Test      Public void createtable () {        new  Configuration (). Configure ();         New Schemaexport (CFG);        Se.create (truetrue);    }

This method is not introduced, execute the method, and see what Hibernate has done?

You can see that in addition to creating a Stu_set_tab table, a table named Hobby_tab is created, and the student_id is set to the foreign key of the hobby_tab.

Test add

Follow the steps above, adding an Add () method:

/*** methods to add*/@Test Public voidAdd () {Transaction tx=NULL; Session Session=NULL; Try{Session=hibernateutils.getsession (); TX=session.begintransaction (); Studentset Student=NewStudentset (); Student.setname ("Zhangsan"); Student.setage (20); @SuppressWarnings ({"Rawtypes", "unchecked"}) Set<String> set=NewHashSet (); Set.add ("Basketball"); Set.add ("Swimming");                        Student.sethobby (set);                                    Session.save (student);        Tx.commit (); }Catch(Hibernateexception He) {if(tx!=NULL) {tx.rollback ();        } he.printstacktrace (); }finally{hibernateutils.closesession (session); }    }

Call the session's Save () method, test the method, and look at what hibernate has done for us?

A little pity, the screen is not large enough to see incomplete, but the idea is complete, these few sentences SQL is still good understanding, is simple insert operation, no longer speak.

Get () method

This test is a little more interesting:

/*** Query Method*/@Test Public voidFindAll () {Transaction tx=NULL; Session Session=NULL; Try{Session=hibernateutils.getsession (); TX=session.begintransaction (); Studentset Stu= (Studentset) session.get (Studentset.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); }    }

In the secondary test, look at the output information of the console:

Why not query the Hobby_tab table? From the program code above, we did not access the Hobby property, improve the program code, add the code to access the Hobby property:

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

Test again, the results should all be guessed,

Hibernate executes two SQL statements, as we expected. First, according to the ID query the basic information of learning, and then according to the ID in the Hobby_tab to query the corresponding data. Didn't you say that before? The SELECT statement is initiated only when the object's non-object-identifier (OID) attribute is accessed, which reflects the lazy loading of hibernate.

Well, yesterday's blog to fill up, a little bit humble, of course, there are a lot of not summed up, there are many needs to be amended, I hope the great God in the garden can give me some comments and suggestions.

Hibernate Learning Series-----(6) Hibernate set set 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.