1、新建java工程
2、在工程中新建一个文件夹lib,用于存放使用Hibernate所用到的jar包
3、选中所有导入的jar包,右击“Build Path”--“add to build path”,将jar导入项目,可以通过右击“build path”----“remove from build path ”删除,所需要的jar包如下:
4、右击“src”,新建2个文件夹,entity和utils。
entity用来存放POJO(Plain Ordinary Java Object)简单的Java对象,实际就是普通JavaBeans,是为了避免和EJB混淆所创造的简称。
utils用来存放工具类
5、在entity文件夹中新建Person类,实现Serializable接口,即实现序列化,对象序列化的主要作用是,方便对象在网络中传输,即把对象变成二进制代码
在Person类中,我们简单设置3个属性,Long pid,String name,String psex。空白处右击“Source”---“Genernate Getters and Setters”--"Select all"--"ok"
6、在entity包中新建持久化对象和表的映射文件,其固定格式为:*.hbm.xml,这是以类名命名的映射文件,需要和po放在同一目录下,myeclipse中新建XML文件,使用Myeclipse Hibernate Mapping Editor打开即可
内容如下:
<?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>
<!--
用来描述一个持久化类
name 类的全名
table 可以不写 默认值和类名一样
catalog 数据库的名称 一般不写
-->
<class name="entity.Person">
<!--
标示属性 和数据库中的主键对应
name 属性的名称
column 列的名称
type 通常用来指定hibernate映射数据类型
-->
<id name="pid" column="pid" length="200" type="java.lang.Long">
<!--
主键的产生器
就该告诉hibernate容器用什么样的方式产生主键
increment 表示自增
-->
<generator class="increment"></generator>
</id>
<!--
描述一般属性
其他与上相似
-->
<property name="pname" column="pname" length="20" type="string">
</property>
<property name="psex" column="psex" length="10" type="java.lang.String"></property>
</class>
</hibernate-mapping>
7、右击“src”,新建hibernate的配置文件,即固定格式为:“hibernate.cfg.xml”,也是新建的一个XML文件,用Myeclipse Hibernate Config Editor 打开即可
其内容如下:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<!--
一个session-factory只能连接一个数据库
-->
<session-factory>
<!--
数据库的用户名
-->
<property name="connection.username">root</property>
<!--
密码
-->
<property name="connection.password">root</property>
<!--
url
-->
<property name="connection.url">
jdbc:mysql://localhost:3306/hibernate
</property>
<!--
当启用hibernate容器的时候,hibernate对表的的处理情况
作用:根据持久化类和映射文件生成表validate 验证表的结构,但不会去创建表,默认值
create-drop 启动时创建表,应用程序结束时,销毁表
create 启动时创建表
update 如果表不存在就创建表,如果表存在,就验证更新表
-->
<property name="hbm2ddl.auto">update</property>
<!--
显示hibernate内部生成的sql语句
-->
<property name="show_sql">true</property>
<property name="myeclipse.connection.profile">mySql</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver
</property>
<!--
方言,指明使用的数据库
-->
org.hibernate.dialect.MySQLDialect
</property>
<mapping resource="myEntity/Person.hbm.xml" />
</session-factory>
</hibernate-configuration>