通过配置文件(hibernate.properties或hibernate.cfg.xml)和映射文件(.hbm.xml)把java对象或持久化对象(Persistent Object,PO)映射到数据库中的数据表,
然后通过操作PO,对数据表中的数据进行增,删,改,查等操作.
Hibernate配置文件主要用来配置数据库连接参数,例如数据库的驱动程序URL,用户名,密码等。
两种格式:hibernate.properties和hibernate.cfg.xml。
一般情况下,hibernate.cfg.xml是Hibernate的默认配置文件。
(1) hibernate.properties:
在Hibernate-3.1的etc目录下有一个hibernate.properties模板。该配置模板文件定义了连接各种数据库所需要的参数。 需要使用hibernate.properties时,修改该模板即可。该模板文件中每一个配置项前面的“#”是注释符号。
(2)hibernate.cfg.xml:
除了要定义Hibernate的各项属性,还要定义程序中用的映射文件(xxx.hbm.xml)。一般情况下是hibernate的默认配置文件。
hibernate.cfg.xml配置文件
<?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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="connection.username">sa</property>
<property name="connection.url">
jdbc:sqlserver://localhost:1433;databaseName=hbDB
</property>
<property name="dialect">
org.hibernate.dialect.SQLServerDialect
</property>
<property name="myeclipse.connection.profile">hbDB</property>
<property name="connection.password">sa</property>
<property name="connection.driver_class">
com.microsoft.sqlserver.jdbc.SQLServerDriver
</property>
<property name="show_sql">true</ property >
<property key="hibernate.connection.autocommit">false</property >
<mapping resource="cn/Customers.hbm.xml" />
</session-factory>
</hibernate-configuration>
hibernate.cfg.xml配置文件属性
属性 |
说明 |
connection.username |
指定连接数据库的用户名 |
connection.url |
指定连接数据库的URL |
dialect |
用于配置hibernate使用的不同的数据类型。 如Oracle、DB2、MS SQL Server、MySQL等。 |
myeclipse.connection.profile |
数据库的配置文件 |
connection.password |
指定连接数据库的密码 |
connection.driver_class |
指定数据库的驱动程序 |
show_sql |
若为true,表示程序在运行时,在控制台输出SQL语句。 |
|
|
mapping |
数据库表和实体的映射信息要在另外的映射文件中定义,但要在配置文件中声明。 |
实体类
Customers实体类要实现implemetns java.io.Serializable接口。
package cn;
public class Customers implements java.io.Serializable {
private Integer id;
private String name;
private Integer age;
public Integer getAge() {
return age;