hibernate的配置方式(一)
hiebernate一共有两种方式,xml文件配置和注释配置,这里就只讲第一种配置方式-xml配置文件配置,而xml文件配置需要配置两个文件,分别是hibernate.cfg.xml和xxx.hbm.xml
1.xxx.hbm.xml配置
这个xxx是和实体类名一样的,例如Customer的实体类,代码如下
public class Customer {
private int id;
private String name;
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
则Customer.hbm.xml的代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<!-- name是实体类的全名
table是表的名称
catalog是数据库的名称
-->
<class name="hibernate.yu.domain.Customer" table="t_customer" catalog="hibernate">
<!--id是用于描述主键的-->
<id name="id" column="id">
<generator class="native"></generator>
</id>
<!--使用property来描述属性与字段-->
<property name="name" column="name"></property>
<property name="address" column="address"></property>
</class>
</hibernate-mapping>
2、hibernate.cfg.xml的配置
hibernate框架核心配置的文件,他主要包含了链接数据库相关的信息,hibernate相关的配置等
代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!--配置关于数据库连接的四个项 driveclass URL username password-->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///hibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
<!--可以将向数据库发送的语句显示出来-->
<property name="hibernate.show_sql">true</property>
<!--格式化sql-->
<property name="hibernate.format_sql">true</property>
<!--hibernate的方言-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!--自动建表-->
<property name="hibernate.hbm2ddl.auto">update</property>
<!--配置hibernate的映射文件所在位置-->
<mapping resource="hibernate/yu/domain2/Customer.hbm.xml"/>
<mapping resource="hibernate/yu/domain2/Order.hbm.xml"/>
</session-factory>
</hibernate-configuration>