hibernate 框架的搭建

方法一

1、下载需要的jar

网址

www.hibernate.org,推荐下载hibernate-distribution-3.3.2.GA-dist.zip

2、部署jar

解压压缩包,拷贝解压文件根目录下的hibernate3.jar以及lib目录下的required文件夹下的所有jar,slf4j-simple-1.5.2需单独下载

3、创建hibernate配置文件

再解压文件的project\etc中,拷贝hibernate.cfg.xml放在src目录下

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

 

<hibernate-configuration>

<session-factory>

<property name="dialect">

org.hibernate.dialect.MySQLDialect

</property>

<property name="connection.url">

jdbc:mysql://localhost:3306/test

</property>

<property name="connection.username">root</property>

<property name="connection.password">123456</property>

<property name="connection.driver_class">

com.mysql.jdbc.Driver

</property>

<property name="myeclipse.connection.profile">MySql</property>

<property name="show_sql">true</property>

<property name="format_sql">false</property>

<mapping resource="entity/Users.hbm.xml" />

</session-factory>

</hibernate-configuration>

4、创建实体类和实体映射文件

package entity;

public class Users implements java.io.Serializable {

 

private static final long serialVersionUID = 1L;

private Integer id;

private String name;

private String password;

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 getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

 

}

 

 

<?xml version="1.0" encoding="utf-8"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

    <class name="entity.Users" table="users">

        <id name="id">

            <generator class="native" />

        </id>

        <property name="name"/>

        <property name="password"/>

    </class>

</hibernate-mapping>

 

5、使用hibernate操作数据库

package util;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

 

public class HibUtil {

public static SessionFactory sf=null;

public static Session session=null;

public static Configuration cfg=new Configuration().configure();

public Session getSession(){

 sf=cfg.buildSessionFactory();

 session=sf.openSession();

return session;

}

public void closeAll(){

if(session!=null){

session.close();

}

if(sf!=null){

sf.close();

}

}

}

 

方法二

平台:myeclipse 8.6

前期准备:配置数据库连接

1.打开窗体

2.鼠标单击任意一个,点击右键->New

3.如图,点击finish

Hibernate配置

1、选择所要构建hibernate的项目,右键->MyEclipse->Add Hibernate Capabilities,如下图

2.所选项如下图,然后next

3.直接next

4.选择使用的数据库

5.可以不创建SessionFactory,点击finish

6.添加实体类和实体映射文件(注:数据库中已存在相关的表),打开起初配好的的数据库连接,选择要映射的表

7.点击右键,选择Hibernate Reverse Engineering

8.配置如图所示,next

9.直接next

10.选择表,配置如图,finish