One-to-one and one-to-many associated operation practices of hibenate

Source: Internet
Author: User

One-to-one Application Association for cascading addition of data
(Job: implements the cascading deletion function)
Create an idcard-type attribute in the record class and the corresponding set ()/get () method. The key code is as follows:

Private idcard;
Public void setidcard (idcard ){
This. idcard = idcard;
}
Public idcard getidcard ()
{Return idcard;
}
In the record. HBM. xml file, map the association from the record class to the idcard class. The key code is as follows:
<One-to-one name = "idcard" class = "mrgf. idcard" cascade = "all"/>
The cascade attribute is used to set the level of the cascade operation object. Its optional values and usage methods are as follows:
Value Options
The default value of none. Cascade operations are not performed.
Save-Update: when the current object is saved or split, the associated object is saved or updated in cascade mode.
Delete: When deleting the current object, cascading deletion of the associated object
ALL: when the current object is saved, updated, or deleted, it is Cascade saved, updated, or deleted.

Create a record-type attribute in the idcard class and the corresponding set ()/get () method. The key code is as follows:
Private record;
Public void setrecordid (INT recordid ){
This. recordid = recordid;
}
Public record getrecord (){
Return record;
}
}
In the idcard. HBM. xml file, map the association from the idcard class to the idcard class. The key code is as follows:
<Export-to-one name = "record" class = "mrgf. Record" unique = "true" column = "record_id"/>
This example uses foreign key Association. When the unique attribute value is set to true, it indicates one-to-one association. Its default value is false (one-to-Multiple Association ), the column attribute value is the foreign key field name of the ing table.

The add () method of Hibernate is responsible for Object Persistence. The complete code is as follows:
Package mrgf;

Import org. hibernate. cfg. configuration;
Import org. hibernate. sessionfactory;
Import org. hibernate. Session;
Import org. hibernate. transaction;
Import org. hibernate. query;
Import java. util. List;
Import java. Io .*;

Public class hibernate {
Public hibernate (){
}

// Load the hibernate configuration information in the static fast mode
Private Static sessionfactory;
Static {
Try {
Configuration Config = new configuration (). Configure ();
Sessionfactory = config. buildsessionfactory ();
} Catch (exception e ){
System. Out. println ("------ An exception is thrown during hibernate initialization. The content is as follows :");
E. printstacktrace ();
}
}

Private session = NULL;
Private transaction Tx = NULL;

// Add an object
Public void add (record, idcard ){
// Open the session and enable the transaction
Session = sessionfactory. opensession ();
Tx = session. begintransaction ();
// Establish association and make it persistent
Record. setidcard (idcard );
Idcard. setrecord (record );
Session. Save (record); // here, only the instance record is persistent. Run this example and you will find that both instances are persistent. This is because the cascade attribute value is set

Change it to none for the purpose of "all" and the idcard instance will not be associated.
// Submit a transaction and close the session
TX. Commit ();
Session. Close ();
}

// Retrieve the object
Public list query (string hql ){
// Open the session and enable the transaction
Session = sessionfactory. opensession ();
Tx = session. begintransaction ();
// Retrieve data
Query query = session. createquery (hql );
List result = query. List ();
// Submit a transaction and close the session
TX. Commit ();
Session. Close ();
Return result;
}

// Solve Chinese garbled characters in Form submission
Public String tochinese (string Str ){
String result = NULL;
Try {
Result = new string (Str. Trim (). getbytes ("iso8859_1"), "gb2312 ");
} Catch (unsupportedencodingexception ex ){
}
Return result;
}

}

Query. jsp usage
String name = request. getparameter ("name ");
.. // Some code for obtaining parameters is omitted here
Record r = New Record ();
R. setname (name );
.. // Some code for obtaining parameters is omitted here
Idcard id = new idcard ();
Id. settype (type );
Id. setnumber (number );

Hibernate H = new hibernate ();
H. Add (R, ID); // call the custom Method
Search
List result = H. Query ("from record where name = '" + name + "'");
<TD> credential type: <% = record. getidcard (). GetType () %> </TD>
<TD> credential number: <% = record. getidcard (). getnumber () %> </TD>
This is also the role of cascade operations. Only the record class is retrieved here.

One-to-multiple application Association for Cascade operations
Merchandise class
Private merchsort;
Public void setmerchsort (merchsort ){
This. merchsort = merchsort;
}
Public merchsort getmerchsort (){
Return merchsort;
}
Merchandise. HBM. xml
<Example-to-one name = "merchsort" column = "merchsort_id" class = "mrgf. merchsort" cascade = "all" lazy = "false"/>

Merchsord class
Private set merchandises = new hashset ();
Public set getmerchandises (){
Return merchandises;
}

Public void setmerchandises (set merchandises ){
This. merchandises = merchandises;
}

Merchsort. HBM. xml
<Set name = "merchandises" cascade = "all" lazy = "false" inverse = "true">
<Key column = "merchsort_id"/>
<One-to-learn class = "mrgf. merchandise"/>
</Set>

Success. jsp
Hibernate hibernate = new hibernate ();
Merchsort = new merchsort ();
Merchsort. setname (ssort); // 1

Merchandise merchandisea = new merchandise (); // many to many, A and B
Merchandisea. setname (mercha );
Merchandise merchandiseb = new merchandise ();
Merchandiseb. setname (merchb );

Hibernate. Add (merchsort, merchandisea, merchandiseb );
Cascading Data Retrieval
<%
String hql = "from merchsort ";
List list = hibernate. Query (hql );
Iterator itsort = List. iterator ();
While (itsort. hasnext ()){
Merchsort sort = (merchsort) itsort. Next ();
Set set = sort. getmerchandises (); // get the object set of the merchandise class through Association
Iterator itmer = set. iterator ();
While (itmer. hasnext ()){
Merchandise mer = (merchandise) itmer. Next ();
%>
<Tr align = "center">
<TD> <% = Mer. GETID () %> </TD>
<TD> <% = Mer. getname () %> </TD> <! -- Get product name -->
<TD> <% = Mer. getmerchsort (). getname () %> </TD> <! -- Get product category -->
<TD> <% = Mer. getproducingarea () %> </TD>
<TD> <% = Mer. getintroduce () %> </TD>
</Tr>
<%
}
}
%>

Add method of hibernate class
Public void add (merchsort, merchandise merchandisea, merchandise merchandiseb ){
Merchsort. getmerchandises (). Add (merchandisea); // establishes associations between instances.
Merchsort. getmerchandises (). Add (merchandiseb );
Merchandisea. setmerchsort (merchsort );
Merchandiseb. setmerchsort (merchsort );
// Open the session and enable the transaction
Session = sessionfactory. opensession ();
Tx = session. begintransaction ();
// Persistence object
Session. Save (merchsort); // instantiate only the merchsort instance. All three instances are persistent.
// Submit a transaction and close the session
TX. Commit ();
Session. Close ();

}

------------------------------------------------------------------------------

The relationship between tables is created in the database.
The one-to-many relationship can be automatically generated when hibernate creates an object bean.

Cascade = "all" cascade level
Lazy latency refers to whether to retrieve the object associated with the current object at the same time when retrieving the current object.

Multiple-to-one
<Role-to-one name = "bbssection" class = "My. Bean. bbssection" cascade = "all" lazy = "false">
<Column name = "rsid" not-null = "true"/>
</Role-to-one>
1-to-many
Private set bbstopics = new hashset (0 );
Public set getbbstopics (){
Return this. bbstopics;
}

Public void setbbstopics (set bbstopics ){
This. bbstopics = bbstopics;
}

<Set name = "bbstopics" inverse = "true" cascade = "all" lazy = "false">
<Key>
<Column name = "tuid" not-null = "true"/>
</Key>
<One-to-define class = "My. Bean. bbstopic"/>
</Set>
Set

Less. Get more (). Add (one of multiple );
Less. Get more (). Add (one of multiple );

-------------------------------------------------------------------------------

1-to-many Addition
// Add an object
Public void add (merchsort, merchandise

Merchandisea, merchandise merchandiseb ){
Merchsort. getmerchandises (). Add (merchandisea );
Merchsort. getmerchandises (). Add (merchandiseb );

// Add method of hashset. To add multiple objects
Merchandisea. setmerchsort (merchsort );
Merchandiseb. setmerchsort (merchsort );
// Open the session and enable the transaction
Session = sessionfactory. opensession ();
Tx = session. begintransaction ();
// Persistence object
Session. Save (merchsort );
// Submit a transaction and close the session
TX. Commit ();
Session. Close ();

}

 

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.