下载hibernate.hibernate-distribution-3.3.1.GA-dist后需引入hibernate3.jar,以及lib\required下的6个jar包。
antlr-2.7.6.jar,commons-collections-3.1.jar,dom4j-1.6.1.jar,javassist-3.4.GA.jar,jta-1.1.jar,slf4j-api-1.5.2.jar。
还需要下载一个slf4j-1.5.2,引入其中的 slf4j-log4j12-1.5.2.jar 这个主要是slf4j-api-1.5.2.jar的实现,在hibernate3.3.1中不存在会报错。slf4j-api-1.5.2.jar用到了log4j所以还要引入log4j-1.2.15.jar。为了建立与mysql的连接需要引入mysql-connector-java-5.1.6-bin.jar
用Eclipse新建工程, 把上述的jar包给引入, 同时再引入数据库的连接包.
1. 建立POJO(相当于DAO模式中的Domain Object)类与在数据库创建相应的表.
show create table user;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=18 DEFAULT CHARSET=latin1
package domain;
public class User {
private int id;
private String name;
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
2. 编写映射文件User.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="domain">
<class name="User">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
</class>
</hibernate-mapping>
3. 编写Hibernate.cfg.xml配置文件:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="foo">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="domain/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
4. 写个测试类:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import domain.User;
public class Test01 {
public static void main(String[] args){
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tran = session.beginTransaction();
User user = new User();
user.setName("Biao Huang");
session.save(user);
tran.commit();
session.close();
}
}
到此, 一个最简单的Hibernate在eclipse中就完成了.