Preparation tools
- Hibernate3.5.3
- Eclipse Java ee ide for Web Developers. Version: Helios
- MySQL5.5
Environment configuration setup
- Install and configure Eclipse, JRE, and other environments.Configure system environment variables
- Download the hibernate version
Create a simple database
Create a database table in MySQL
create database testssh;use testssh;create table user( u_id int not null auto_increment, u_name varchar(30), primary key(u_id));
Create a hibernate Project
1. File-> New-> Dynamic Web Project-> Fill in the Project information (hibernatedemo)-> finish the Project name in this example: hibernatedemo
2. Copy the hibernate jar package to the project hibernatedemo/WebContent/WEB-INF/lib
3. Compile hibernate. cfg. xml in the src directory to configure the database information.
<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
4. Create the com. entity package under src for object objects, write User-class, and write the User. hbm. xml ing file under the same directory. You can use XML to configure ing or annotate the ing to database tables.
User. java
package com.entity;public class User { private Integer id; private String name; 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; }}
Compile User. hbm. xml and configure hibernate ing in hibernate. cfg. xml.
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
5. Test. Compile the test class in the com. test package
public class Testhibernate { public static void main(String[] args) { Configuration cfg=new Configuration().configure(); SessionFactory sf=cfg.buildSessionFactory(); Session session =sf.openSession(); Transaction tx=session.beginTransaction(); User user=(User)session.get(User.class, 1); System.out.println(user.getId()); System.out.println(user.getName()); session.close(); sf.close(); }}
6. The configuration process of the entire hibernate project is finished!