Hibernate's One-to-many XML article One

Source: Internet
Author: User
Tags getmessage set set
After work to get a bit of hibernate ORM relationship, dare not say in-depth, only as a little summary after learning: Hibernate in the Java EE Web Development has been widely used, to understand some of Hibernate's common operations is very necessary. The following is a simple example to understand Hibernate ont-to-many/many-to-one bidirectional configuration, inverse, Cascade Common configuration: First, create a simple database table:user< users > and book < books > Here is the assumption that the relationship between user and book is one-to-many, creating the code as follows: MySQL: (1) Create user Table:drop Table IF EXISTS ' user '; CREATE TABLE ' user ' (' uid ' int (one) not null auto_increment, ' uname ' varchar (255) is not NULL, PRIMARY KEY (' uid ')) E Ngine=innodb auto_increment=28 DEFAULT charset=latin1; (2) Create book Table:drop Table IF EXISTS ' book ';   CREATE TABLE ' book ' (' Bid ' int (one) not null auto_increment, ' bname ' varchar () ' is not null, ' buid ' int (one) ' is not NULL, PRIMARY key (' bid '), key ' Fk_user ' (' BUiD '), CONSTRAINT ' Fk_user ' FOREIGN KEY (' buid ') REFERENCES ' USER ' (' uid ')) Engine=innodb auto_increment=38 DEFAULT charset=latin1;
Second, write the Entity Class of the printing, here is the XML configuration method, the relevant annotation will be published in a future article, (1) User Entity:public Class user implements java.io.Serializable {//Fields private Integer uid; private String uname; private Set books = new HashSet (0);//one-to-m Any relationship, as one party uses set to store the data representation of the many party
Constructors
Public User () {} get .... Set ... Method
(2) Book Entity:public class Book implements Java.io.Serializable {//fields private Integer bid; private user user;//one party The Entity object < database relationship is associated by a foreign key, that is: The Book table has the ID of the user table foreign key > Private String bname;
Constructors Public book () {}
Get .... Set ... Method
Third, relevant ORM insinuate file: (1) User.hbm.xml:

(2) Book.hbm.xml:

OK, so the above configuration is complete, here is the test code: First, test cascading add:public static void Onttomanyadd_user () {//Get session/and open transaction sessionfactory factory = Hibernatesessionfactory.getsessionfactory (); Session session = Factory.opensession (); Transaction st = Session.begintransaction (); try {
Create user Object User user = new user (); User.setuname ("A");
Creates a book object and stores it in the set set Book_set = new HashSet (); Book Book1 = new book (); Book1.setbname ("Java"); Book Book2 = new book (); Book2.setbname ("C + +"); Book BOOK3 = new book (); Book3.setbname ("Net");
Book_set.add (BOOK1); Book_set.add (BOOK2); Book_set.add (BOOK3); Set user Object properties in book Object Note: Be sure to set this property if not set, you will not be able to cascade add Book book1.setuser (user); Book2.setuser (user); Book3.setuser (user);
User.setbooks (Book_set);
Session.save (user); St.commit (); System.out.println ("Add success!"); } catch (Exception e) {System.out.println (E.getmessage ()); St.rollback ();} finally {session.close ();}} The above code test results are as follows:Hibernate:insert into Hibernate_db.user (uname) VALUES (?) Hibernate:insert into Hibernate_db.book (BUiD, bname) VALUES (?,?) Hibernate:insert into Hibernate_db.book (BUiD, bname) VALUES (?,?) Hibernate:insert into Hibernate_db.book (BUiD, bname) VALUES (?,?) added successfully! Here are a few things to keep in mind in the code above and in the configuration:<1>, Book1.setuser (user); Book2.setuser (user); Book3.setuser (user); Sets the user object property in the book object because the UID field in the Book table in the database is not NULL so you need to set the property for the user object in the book entity, and if not set, an error occurs:
Hibernate:insert into Hibernate_db.user (uname) VALUES (?) Hibernate:insert into Hibernate_db.book (BUiD, bname) VALUES (?,?) could not insert: [Com.model.Book] Prompt cannot be insert in book object 。 <2>, User.hbm.xml in the configuration of Cascade, this property can be simply understood as: "Cascade operation Type", here cascade= "all" means: regardless of the current operation of the User object is added or deleted or checked Will cascade the collection of books in user and, of course, can be set to other property values, such as: Save-update 、、、、 the use of Cascade: when you manipulate one or some of the elements, but you need to cascade to the action to another element, you need to configure this. For example, the user object here: When adding a user needs to cascade add N book then you need to set the Cascade property for the book collection object in user books, of course, in book is also set cascade properties to Cascade operation User Object.
Second, To test a cascading query:public static void Onttomanyselect () {Sessionfactory factory = Hibernatesessionfactory.getsessionfactory (); Session session = Factory.opensession (); try {//Get the user object user user = (user) Session.get (user.class, 27); System.out.println ("user_name:" + user.getuname ()); Session.close (); // Code 1if (user! = null) {//Gets the books collection data from the user object Iterator iter = User.getbooks (). Iterator (); while (Iter.hasnext ()) {Book b = it Er.next (); System.out.println ("\ t book_name:" + b.getbname ());}}
} catch (Exception e) {System.out.println (E.getmessage ());} finally {session.close ();}}
There is one detail in the cascading query code above that we need to be aware of: The lazy attribute configuration in the Set inside the User.hbm.xml, meaning lazy loading, can be simply understood as: "When loading one or more elements, is it possible to load other elements that are associated with this element", In hibernate default configuration, the value of lazy property is true, that is: Do not take the initiative to load its related elements, so there is a benefit, that is, when we need to query, how to be considered when it is necessary. For example above: Iterator iter = User.getbooks (). Iterator (); This is where hibernate emits an SQL statement to query when we use the associated element in the user object. However, there is also a problem: if the session is closed, Hibernate will not be able to retrieve the object until it is used (e.g. code 1 in the comment). This time, if you read its related properties again in the view layer or in the background, it will appear:
Session was already closed errorSo in the use of the need to see their own needs to configure the lazy.


The above has outlined the two-way relationship between One-to-many and Many-to-one, in fact, there are a lot of things need our actual operation will encounter and learn.

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.