Zero-configuration Annotation and Hibernate Annotation configuration for hibernate

Source: Internet
Author: User

Zero-configuration Annotation and Hibernate Annotation configuration for hibernate

We recommend that you use Annotation to manage the ing between object classes and data tables in JPA specifications, so as to avoid maintaining two files (Java object classes and XML ing files) at the same time ), combine the ing information (written in Annotation) with the object class.

Below I will use eclipse to build a small query example that replaces *. hbm. xml with simple annotations. (P.s does not recommend using Myeclipse. It is very convenient, but it is not reliable for beginners)

1. Create a table in the database

 

2. Generate the corresponding hibernate. cfg. xml file

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE hibernate-configuration PUBLIC "-// Hibernate/Hibernate Configuration DTD 3.0 // EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> Note: When generating the cfg. xml file, create Hibernate Console Configuration

3. Generate reverse engineering for hibernate. reveng. xml

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE hibernate-reverse-engineering PUBLIC "-// Hibernate/Hibernate Reverse Engineering DTD 3.0/EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd"> In the Eclipse interface toolbar, choose Hibernate code generation Configuration, a new Configuration.

4. Select the Exporters option. The next step is the focus !!!

Select the two items selected. hbm. xml.

Click Run.

5. Only the object class Commodity. java corresponding to the data table is generated, and the coming file Commodity. hbm. xml corresponding to the object class is not generated. Open the object class.

package com.zzh;// Generated 2016-8-28 9:42:01 by Hibernate Tools 4.3.1.Finalimport javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import static javax.persistence.GenerationType.IDENTITY;import javax.persistence.Id;import javax.persistence.Table;/** * Commodity generated by hbm2java */@Entity@Table(name = "commodity", catalog = "zzh")public class Commodity implements java.io.Serializable {    private Integer id;    private String name;    private Double price;    private String unit;    private String category;    private String description;    private Integer seller;    public Commodity() {    }    public Commodity(String name, Double price, String unit, String category, String description, Integer seller) {        this.name = name;        this.price = price;        this.unit = unit;        this.category = category;        this.description = description;        this.seller = seller;    }    @Id    @GeneratedValue(strategy = IDENTITY)    @Column(name = "Id", unique = true, nullable = false)    public Integer getId() {        return this.id;    }    public void setId(Integer id) {        this.id = id;    }    @Column(name = "name", length = 100)    public String getName() {        return this.name;    }    public void setName(String name) {        this.name = name;    }    @Column(name = "price", precision = 11)    public Double getPrice() {        return this.price;    }    public void setPrice(Double price) {        this.price = price;    }    @Column(name = "unit", length = 50)    public String getUnit() {        return this.unit;    }    public void setUnit(String unit) {        this.unit = unit;    }    @Column(name = "category", length = 100)    public String getCategory() {        return this.category;    }    public void setCategory(String category) {        this.category = category;    }    @Column(name = "description", length = 1000)    public String getDescription() {        return this.description;    }    public void setDescription(String description) {        this.description = description;    }    @Column(name = "seller")    public Integer getSeller() {        return this.seller;    }    public void setSeller(Integer seller) {        this.seller = seller;    }}

The @ Entity annotation is used to indicate that the current class is an Entity Bean and needs to be persisted. The @ Table annotation is used to map the commodity of the data Table and the Commodity of the persistence class, @ Id annotation specifies the ID attribute of the current persistence class. The @ GeneratedValue annotation specifies the ID to indicate the generator, the @ Column annotation specifies the fields in the data table corresponding to the current attribute, and the name specifies the field name; unique indicates whether it is unique and nullable specifies whether it can be null.

6. Configure the ing information in hibernate. cfg. xml.

<Mapping class = "com. zzh. Commodity"/>

Note that class ing is followed by class. If *. hbm. xml is configured, It is resource.

7. Add the Session factory class HibernateUtil to get the Session

Package com. zzh. utl; import org. hibernate. session; import org. hibernate. sessionFactory; import org. hibernate. boot. registry. standardServiceRegistry; import org. hibernate. boot. registry. standardServiceRegistryBuilder; import org. hibernate. cfg. configuration; public class HibernateUtil {private static SessionFactory sessionFactory; private static Session session; static {// create a Configuration object and read hibernate. cfg . Xml file, complete the Initialization Configuration config = new Configuration (). configure (); StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder (). applySettings (config. getProperties (); StandardServiceRegistry ssr = ssrb. build (); sessionFactory = config. buildSessionFactory (ssr);} // get SessionFactory public static SessionFactory getSessionFactory () {return sessionFactory;} // get Session public static Sess Ion getSession () {session = sessionFactory. openSession (); return session;} // close Session public static void closeSession (Session session) {if (session! = Null) {session. close ();}}}View Code

8. Create a class ZhuShi. java with JUnit for testing.

package anno;import static org.junit.Assert.*;import java.util.List;import org.hibernate.Query;import org.hibernate.Session;import org.junit.After;import org.junit.Before;import org.junit.Test;import org.hibernate.annotations.*;import com.zzh.Commodity;import com.zzh.utl.HibernateUtil;public class ZhuShi {    Session session = null;    @Before    public void setUp() throws Exception {        session = HibernateUtil.getSession();    }    @After    public void tearDown() throws Exception {        session.close();    }    @Test    public void test() {        String hql = " from Commodity ";        Query query = session.createQuery(hql);        List<Commodity> c = query.list();        for (Commodity commodity : c) {            System.out.println("name"+commodity.getName());        }    }}

9. The entire file has been formed

Run the test and obtain the result.

10. Summary

A large number of *. hbm. xml files are no longer needed. All configurations are directly configured in the persistence class through the Annotation.

11. Personal thoughts

I did not need to annotate it before. Later, I had to debug the path for half a day. At that time, I was stupid. I told you about it. I used reverse engineering to generate entity classes, and *. hbm. xml file, then hbm. the xml file is as follows: (See What I drew in red)

 

I didn't care because it was a tool that helped me generate it. Then I happily went to configure the cfg. xml file (as shown below ):

 

All files are as follows:

To ensure that everything went well, JUnit was used for testing:

The entity class cannot be found. Sorry, I did it step by tool. Why? I discovered it later *. hbm. the class tag name in xml has an error. You must add the package name:

Test again:

It succeeded. This does not mean *. hbm. xml is not good. In fact, we mainly blame ourselves for lack of experience and use of tools. For Beginners, we recommend that you use multiple tools *. hbm. xml files are better. After all, they can better understand the elements and ing information and methods. However, after being proficient, annotations are simpler and easier to manage.

After that, I will continue to write some annotation cases for association ing (for example, bidirectional one-to-many and bidirectional many-to-many). If you think it is good, please follow me or give me a thumbs up. Thank you for watching it!

--- References: detailed introduction and integration of Struts2 + Spring3 + Hibernate framework technology case

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.