Getting started with Hibernate

Source: Internet
Author: User

Getting started with Hibernate

Today, I have been busy all day and finally set up my first Hibernate program. cfg. the xml issue has been fixed for a long time, but I still understand it at last. Let's talk about the process below.

First, install the Hibernate Tools plug-in your eclipse to create the cfg. CRF and hbm. xml files. Then create and configure the hibernate. cfg. xml file:

Add yi

Of course, you need to add the hibernate jar package and musql driver at the beginning. Because I use maven to manage projects, I can simply add them to the maven pom file.

Add some things in hibernate. cfg. xml:

1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 <! DOCTYPE hibernate-configuration PUBLIC 3 "-// Hibernate/Hibernate Configuration DTD 3.0 // EN" 4 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 5 

 

What is hibernate after the ninth line url? CharacterEncoding = UTF-8 is the name of the database to be operated by hibernate. You need to first create:

create database hibernate character set 'utf8'

The 19-row Cat class is the POJO Entity class that you need to create on your own. The Entity class (Entity) it refers to the Java class mapped to the database. After @ Entity is used, Cat is declared as an Entity class. The corresponding Table name (@ Table), primary key (@ Id), and common attribute (@ Column) must be configured for the object class.

  1 package com.lxiao.model;  2   3   4 import java.util.Date;  5   6 import javax.persistence.Column;  7 import javax.persistence.Entity;  8 import javax.persistence.GeneratedValue;  9 import javax.persistence.GenerationType; 10 import javax.persistence.Id; 11 import javax.persistence.JoinColumn; 12 import javax.persistence.ManyToOne; 13 import javax.persistence.Table; 14 import javax.persistence.Temporal; 15 import javax.persistence.TemporalType; 16  17 @Entity 18 @Table(name="tb_cat") 19 public class Cat { 20  21     @Id 22     @GeneratedValue(strategy = GenerationType.AUTO) 23     private Integer Id; 24      25     @Column(name = "name") 26     private String name; 27      28     @Column(name = "description") 29     private String description; 30      31     @Column(name = "age") 32     private Integer age; 33      34     @Column(name="sex") 35     private String sex; 36      37     @ManyToOne 38     @JoinColumn(name = "mother_id") 39     private Cat mother; 40      41     @Temporal(TemporalType.TIMESTAMP) 42     @Column(name = "createDate") 43     private Date createDate; 44  45     public Integer getId() { 46         return Id; 47     } 48  49     public void setId(Integer id) { 50         Id = id; 51     } 52  53     public String getName() { 54         return name; 55     } 56  57     public void setName(String name) { 58         this.name = name; 59     } 60  61     public String getDescription() { 62         return description; 63     } 64  65     public void setDescription(String description) { 66         this.description = description; 67     } 68  69     public Integer getAge() { 70         return age; 71     } 72  73     public void setAge(Integer age) { 74         this.age = age; 75     } 76  77     public String getSex() { 78         return sex; 79     } 80  81     public void setSex(String sex) { 82         this.sex = sex; 83     } 84  85     public Cat getMother() { 86         return mother; 87     } 88  89     public void setMother(Cat mother) { 90         this.mother = mother; 91     } 92  93     public Date getCreateDate() { 94         return createDate; 95     } 96  97     public void setCreateDate(Date createDate) { 98         this.createDate = createDate; 99     }100 101 }

It is worth mentioning that after defining the private variable of play le, The POJO class can use eclipse to automatically generate the getter and setter methods, eliminating the hassle of handwriting.

Then create the Cat. hbm. xml file and add your POJO class. Here I am Cat. When using the Hibernate tools tool, select Add class,

Next is all the way, and then at hibernte. cfg. you can configure the object class in xml with <mapping resource = "config/Cat. hbm. xml ">. This is the configuration for the xml file. If it is @ annotation configuration, use <maping class =" com. lxiao. model. cat ">

Then we write a HibernateUtil class to load the config file hibernate. cfg. xml:

 1 package com.lxiao.hibernate; 2  3 import org.hibernate.SessionFactory; 4 import org.hibernate.cfg.Configuration; 5  6 public class HibernateUtil { 7     private static final SessionFactory factory; 8      9     static{10         try{11             factory = new Configuration().configure("config/hibernate.cfg.xml").buildSessionFactory();12         }catch(Throwable e){13             System.out.println("Initial sesionFactory failed..."+e);14             throw new ExceptionInInitializerError(e);15         }16     }17     18     public static SessionFactory getSessionFactory(){19         return factory;20     }21 }

The object class for loading xml Configuration must use Configuration to load the Hibernate Configuration.

Finally, we need to use the Cat class so that Hibernate can automatically create tables for us and perform database operations. The whole process is: Hibernate saves the data. It first starts a session (equivalent to the Connection in JDBC) through sesonFactory, then starts a Transaction, then saves the code and submits the Transaction, close the session. Other database operations are similar. The following is my program:

1 package com. lxiao. hibernate; 2 3 import java. awt. font; 4 import java. util. date; 5 import java. util. list; 6 7 import javax. swing. JOptionPane; 8 9 import org. hibernate. session; 10 import org. hibernate. transaction; 11 12 import com. lxiao. model. cat; 13 14 public class CatTest {15 public static void main (String [] args) {16 Cat motherCat = new Cat (); 17 motherCat. setName ("Mary White"); 18 motherCat. setDescri Ption ("The mama cat... "); 19 motherCat. setCreateDate (new Date (); 20 21 Cat kitty = new Cat (); 22 kitty. setMother (motherCat); 23 kitty. setName ("Kitty"); 24 kitty. setDescription ("Hello Kitty"); 25 kitty. setCreateDate (new Date (); 26 27 Cat midate = new Cat (); 28 mimmy. setMother (motherCat); 29 miits. setName ("miname"); 30 miname. setDescription ("Kitty's little twn sister"); 31 mimmy. setCreateDate (new Date (); 32 33 Session session = HibernateUtil. getSessionFactory (). openSession (); // enable a Hibernate conversation 34 Transaction transaction = session. beginTransaction (); 35 36 session. persist (motherCat); // save mother to database 37 session. persist (kitty); 38 session. persist (miist); 39 40 List <Cat> catlist = session. createQuery ("from Cat "). list (); 41 42 StringBuffer resultBuffer = new StringBuffer (); 43 resultBuffer. append ("All cat in db: \ r \ N \ r \ n "); 44 45 for (Cat cat: catlist) {46 resultBuffer. append ("Cat:" + cat. getName () + ","); 47 resultBuffer. append ("Mothercat:" + (cat. getMother () = null? "No record": cat. getMother (). getName (); 48 resultBuffer. append ("\ r \ n"); 49} 50 transaction. commit (); // submit transaction 51 session. close (); // close the database 52 53 JOptionPane. getRootFrame (). setFont (new Font ("Arial", Font. BOLD, 14); 54 JOptionPane. showMessageDialog (null, resultBuffer. toString (); 55 56 57} 58}

Running result:

My query results in the database are as follows:

In the hibernate. cfg. xml configuration file, we have:

1 <! -- Automatically create the table structure when Hibernate starts --> 2 15 <property name = "hbm2ddl. auto"> create </property>

 

Every time Hibernate deletes a table, it creates a table.

Finally, put my project directory structure:

In short, my first Hibernate program can finally run, and I have learned a lot about the hi-fi ORM framework. It brings a lot of convenience to the database operations during development and is worth learning, learn more.

-- The programmer's path is long and he continues to work hard...

 

Reference books: Return of the King of Java Web Development, edited by Liu Jinghua.

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.