HIbernate3.6环境搭建
一.下载Hibernate环境需要用到的jar包
1.http://sourceforge.net/projects/hibernate/files/hibernate3
2.由于在Hibernate3.6中使用的是slf4j来记录日志,而hibernate3.6的jar包中又没有带有slf4j的实现包,所以这里需要自己另外去下载slf4j的jar包 http://www.slf4j.org/download.html3.MySQL-JDBC驱动:http://www.mysql.com/products/connector/
二.新建Java项目
在Java项目的库文件中加入以下jar包
*HIBERNATE_HOME/hibernate3.jar
*HIBERNATE_HOME/lib/required/*.jar
*HIBERNATE_HOME/lib/jpa/*.jar
*slf4j_HOME/slf4j-nop-1.6.1.jar
*mysql-jdbc驱动
三.在类路径的根目录下创建hibernate配置文件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> <!--数据库连接URL --> <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property> <!--数据库连接驱动 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <!--数据库用户名 --> <property name="hibernate.connection.username">root</property> <!--数据库密码 --> <property name="hibernate.connection.password">root</property> <!--数据库方言 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.show_sql">true</property> <!--方便跟踪sql执行--> <property name="hibernate.show_sql">true</property> </session-factory> </hibernate-configuration>
四.编写实体类User.java
public class User { private String id; private String name; private Date createTime; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } ........ }
五.编写ORM映射文件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> <class name="com.swpu.hibernate.User"> <id name="id"> <generator class="uuid"/> </id> <property name="name"/> <property name="createTime"/> </class> </hibernate-mapping>
六.修改hibernate.cfg.xml文件,将ORM映射文件配置到hibernate配置文件中
<session-factory> ...... <mapping resource="com/swpu/hibernate/User.hbm.xml"/> ...... </session-factory>
七.编写hbm2ddl工具类,将实体类导出为数据库表
public class ExportDB { public static void main(String[] args) { //读取hibernate.cfg.xml文件 Configuration cfg = new Configuration().configure(); SchemaExport export = new SchemaExport(cfg); export.create(true, true); } }