Hibernate notes-use annotations (annotation) to configure a single (dual) to many-to-one mapping relationship

Source: Internet
Author: User

The previous several are introduced with the configuration file to implement the entity class to the database table mapping, this way is more troublesome, each Pojo class need to write a corresponding *.hbm.xml, undoubtedly increased a lot of code, but also has the advantage is conducive to maintenance, in order to facilitate the development, Hibernate also provides an annotated way to configure the mapping file, very flexible, reduce the redundancy of the configuration file, although maintenance is relatively troublesome, but it is very convenient to develop. Now it's becoming more and more popular to use annotations, a small example of using annotation development.

Suppose there are two tables, a book table, a book category, and it is clear that the books and category are many-to-one relationships. Use annotations should be configured like this:

New book entity class:

//entity class that requires persistence@Entity//multiple tables for entity classes@Table (name= "T_book") Public classBook {//ID PRIMARY Key@Id//set the primary key generation strategy, where auto represents self-growth and native correspondence,
(strategy------represents the primary key generation policy:
Generationtype.auto the default value. Indicates that the ORM frame is automatically selected, corresponding to the native in hibernate;
Generationtype.table use the value of the table one save ID;
Generationtype.identity is generated based on the IDENTITY field of the database;
Generationtype.sequence is generated based on the SEQUENCE field of the database table;)@GeneratedValue (strategy=Generationtype.auto)Private intID; PrivateString name; Private DoublePrice ; PrivateString author; PrivateDate pubDate;//Get/set Method omitted}

New category entity class:

@Entity @table (name= "T_category") Public classCategory {@Id @GeneratedValue (strategy=Generationtype.auto)Private intID; PrivateString name; //configuration @OneToMany at one end (mappedby= "multi-Port attribute")@OneToMany (mappedby= "category")    PrivateSet<book> books=NewHashset<book>();//Get/set Method omitted}

Add two entity classes to the Hibernate.cfg.xml, note that because the class is added, not the XML file, the package name is used between the "." Instead of "/" separated.

This completes the configuration, is not quite simple. Create a new test class below, Test 1: Automatically generate table 2: Save data 3: Read data:

@Test Public voidTestcreatedb () {Configuration cfg=NewConfiguration (). Configure (); Schemaexport SE=NewSchemaexport (CFG); Se.create (true,true); } @Test Public voidTestsave () {Session session=hibernateutil.getsession (); Book Book=NewBook (); Book.setauthor ("Jin Yong"); Book.setname ("Deer Ding kee"); Book.setprice (12.35); Book.setpubdate (NewDate ()); Book Book1=NewBook (); Book1.setauthor (Potatoes); Book1.setname ("Fighting the heavens."); Book1.setprice (22.35); Book1.setpubdate (NewDate ()); Category C1=NewCategory (); C1.setname ("Martial Arts Class");                Book.setcategory (C1); Category C2=NewCategory (); C2.setname ("Fantasy Class");                Book1.setcategory (C2);        Session.save (book);        Session.save (BOOK1);        Session.begintransaction (). commit ();    Session.close (); } @Test Public voidTestget () {Session session=hibernateutil.getsession (); Book B= (book) session.get (book).class, 1); System.out.println ("Book Name:" +b.getname () + ", Category:" +b.getcategory (). GetName ()); System.out.println ("========================="); Category C= (category) session.get (category).class, 1); System.out.print ("Category:" +c.getname () + ", Book Name:"); Iterator<Book> it =c.getbooks (). iterator ();  while(It.hasnext ()) {System.out.print (It.next (). GetName ());        } session.begintransaction (). commit ();            Session.close (); }

Attention:

 1. 4 jar packages to import using annotations: Hibernate-commons-annotations.jar, Hibernate-annotations.jar,ejb3-persistence.jar, Hibernate-jpa-2.0-api-1.0.1.final.jar

2. Using annotations to configure a mapping relationship, the *.hbm.xml file is no longer required, but the mapping relationship is defined as annotations in the entity class.

3. Note under the Javax.persistence package, rather than under Hibernate package, pay special attention.

Hibernate notes-use annotations (annotation) to configure a single (dual) to many-to-one mapping relationship

Related Article

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.