Hibernate's One-to-many XML Chapter

Source: Internet
Author: User
Tags getmessage

(GO) Hibernate's One-to-many XML
Hibernate's ORM relationship,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 ')) Engine=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 (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 {//fieldsprivate Integer uid;private String uname;private Set books = new HashSet (0);//one-to-many off System, as one party uses set to store many-side data representation//Constructors public User () {}get....set ... Method} (2) book Entity:public class Book implements Java.io.Serializable {//fieldsprivate Integer bid;private user user;//on The Entity object < database relationship on the E side is associated by a foreign key, i.e. the ID of the user table in the Book table is >private String bname; Constructorspublic Book () {} Get....set ... Method} Three, about 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");//create book object, and stored 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, will not be able to cascade add bookbook1.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 (?,?) Add success! 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), setting user object properties in the book object, Because the UID field in the Book table in the database is not NULL, you need to set a property for the user object in the book entity, and if you do not set it, 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]Tip You cannot insert the 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 = ITER.N Ext (); 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 is it necessary when? 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.

Hibernate's One-to-many XML Chapter

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.