hibernate是一个开源的对象关系映射框架,它对jdbc进行了轻量级的对象封装,使用它我们可以使用对象编程思想来操作数据库,事实上,在java世界,它已成了ORM框架的代表。下面就一起来学习下hibernate。
一、获取hibernate。从https://www.hibernate.org/网站上可以获取到最新版本的hibernate和相关文档,笔记的例子使用了3.2.5。
二、快速上手。
1、打开myEclipse,新建一个java project,导入hibernate及JDBC相关jar包,就可以配置开发hibernate应用了。注:JDBC包是必需的,且需与数据对应,笔者使用的是mysql5.0数据库。
2、配置hibernte。在src目录下新建一个xml文件,名称为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 >
<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">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="com/eja/hibernate/domain/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory >
<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">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="com/eja/hibernate/domain/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>