Getting started with Hibernate

Source: Internet
Author: User

Getting started with Hibernate

For more information about the basic concepts, see other teaching materials. Here we only record the implementation steps of the first Hibernate program.

Environment Description:

Java Development Tool: eclipse MARS.2 Release (4.5.2)

Hibernate: hibernate-release-4.3.6.Final

Web Container: Tomcat v8.0

Database: MySQL 5.6.19-enterprise-defined cial-advanced

Jdbc driver: mysql-connector-java-commercial-5.1.30-bin.jar

1. Download hibernate.

2. Download The jdbc driver file.

3. Create a web project in eclipse and name it firsthibernate.

4. copy all jar files under the hibernate/lib/required folder and jdbc driver files (this file is also downloaded) to the project's WEB-INF/lib folder, copy hibernate under hibernate/project/etc. cfg. xml file to the src directory of the project.

5. create an object Cat. There are two methods to configure the object class in Hibernate: XML file configuration and @ annotation configuration. In this example, @ annotation configuration is used, the meanings of related annotations are described in the Code as follows:

Package com. levice. firsthibernate. bean; import java. util. date; import javax. persistence. column; import javax. persistence. entity; import javax. persistence. generatedValue; import javax. persistence. generationType; import javax. persistence. id; import javax. persistence. joinColumn; import javax. persistence. manyToOne; import javax. persistence. table; import javax. persistence. temporal; import javax. persistence. tempora LType; @ Entity // annotation Entity indicates that the class can be persisted by Hibernate @ Table (name = "tb_cat ") // specify the name of the data table corresponding to the Entity public class Cat {@ Id // specify the column as the primary key. It is best not to use the original type such as int @ GeneratedValue (strategy = GenerationType. AUTO) // The primary key Type auto indicates that the primary key is an AUTO-incrementing private Integer id; @ Column (name = "name") // specifies the name of the database table corresponding to this attribute, when the Column name is the same as the attribute name, this annotation can omit private String name; @ Column (name = "description") private String description; @ ManyToOne // specifies the relationship between object classes, in this example, @ JoinColumn (name = "mother_id") private Cat mother; @ Temporal (TemporalType. TIMESTAMP) // DATE type (Date, TIME, or TIMESTEMP) @ Column (name = "birthday") private DATE birthday; // getters and setters public Integer getId () {return id;} public void setId (Integer id) {this. id = id;} public String getName () {return name;} public void setName (String name) {this. name = name;} public String getDescription () {return description;} public void setDescription (String description) {this. description = description;} public Cat getMother () {return mother;} public void setMother (Cat mother) {this. mother = mother;} public Date getBirthday () {return birthday;} public void setBirthday (Date birthday) {this. birthday = birthday ;}}

 

6. modify the configuration file hibernate. cfg. xml. The content and comments are as follows:

<! DOCTYPE hibernate-configuration PUBLIC "-// Hibernate/Hibernate Configuration DTD 3.0 // EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 

 

7. initialize the database and create the database hibernate in MySQL. The SQL code is as follows:

create database hibernate;

 

8. to configure HibernateUtil, modify the HibernateUtil. java file, which is included in the downloaded hibernate file, but I did not successfully debug it when I copied it, so I used a later version of HibernateUtil. The purpose of this file is to get SessionFactory to get the Session. The methods for getting SessionFactory in hiberate of different versions are different. Here we can create a new HibernateUtil. java file and copy the following code.

package com.levice.firsthibernate.util;import org.hibernate.SessionFactory;import org.hibernate.cfg.AnnotationConfiguration;@SuppressWarnings("deprecation")public class HibernateUtil {    private static final SessionFactory sessionFactory;    static{        try{            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();        }catch(Throwable ex){            System.err.println("Initial SessionFactory creation failed.");            throw new ExceptionInInitializerError(ex);        }    }        public static SessionFactory getSessionFactory(){        return sessionFactory;    }}

 

9. Execute the Hibernate program and create a CatTest class containing the main function. The code and comments are as follows:

Package com. levice. firsthibernate. test; import java. awt. font; import java. util. date; import java. util. list; import javax. swing. JOptionPane; import org. hibernate. session; import org. hibernate. transaction; import com. levice. firsthibernate. bean. cat; import com. levice. firsthibernate. util. hibernateUtil; public class CatTest {public static void main (String [] args) {// TODO Auto-generated method stub/* initialize several Cat Information */Cat mother = new Cat (); mother. setName ("Mother White"); mother. setDescription ("This is mother cat"); mother. setBirthday (new Date (); Cat kitty = new Cat (); kitty. setMother (mother); kitty. setName ("Kitty"); kitty. setDescription ("This is Kitty"); kitty. setBirthday (new Date (); Cat tom = new Cat (); tom. setMother (mother); tom. setName ("Tom"); tom. setDescription ("This is Tom"); tom. setBirthday (new D Ate (); @ SuppressWarnings ("static-access") Session session = new HibernateUtil (). getSessionFactory (). openSession (); // obtain the session and open it. Enable a Hibernate session Transaction trans = session. beginTransaction (); // starts a transaction session. persist (mother); // save the mother to the database session. persist (kitty); session. persist (tom); @ SuppressWarnings ("all") List <Cat> catList = session. createQuery ("from Cat "). list (); // query all cat StringB in the database Uffer result = new StringBuffer (); result. append ("all cats: \ r \ n"); for (Cat cc: catList) {result. append ("name:" + cc. getName () + "\ n"); result. append ("mother:" + (cc. getMother () = null? "Null": cc. getMother (). getName () + "\ n"); result. append ("description:" + cc. getDescription () + "\ r \ n");} trans. commit (); // submit the transaction session. close (); // close the Hibernate session // use Swing to display the query result JOptionPane. getRootFrame (). setFont (new Font ("Arial", Font. BOLD, 14); JOptionPane. showMessageDialog (null, result. toString ());}}

10. Run CatTest and you can see the following output:

The SQL statements output by the console are as follows:

Hibernate: alter table tb_cat drop foreign key FK_dix3h50rxo8ahrcu5roir75n1Hibernate: drop table if exists tb_catHibernate: create table tb_cat (id integer not null auto_increment, birthday datetime, description varchar(255), name varchar(255), mother_id integer, primary key (id))Hibernate: alter table tb_cat add constraint FK_dix3h50rxo8ahrcu5roir75n1 foreign key (mother_id) references tb_cat (id)Hibernate: insert into tb_cat (birthday, description, mother_id, name) values (?, ?, ?, ?)Hibernate: insert into tb_cat (birthday, description, mother_id, name) values (?, ?, ?, ?)Hibernate: insert into tb_cat (birthday, description, mother_id, name) values (?, ?, ?, ?)Hibernate: select cat0_.id as id1_0_, cat0_.birthday as birthday2_0_, cat0_.description as descript3_0_, cat0_.mother_id as mother_i5_0_, cat0_.name as name4_0_ from tb_cat cat0_

 

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.