版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1337038
(本文所用hibernate版本为hibernate-3.2.0;数据库为MySQL 5.5.24;数据库驱动为mysql-connector-java-5.1.20-bin.jar)
这里以一个普通的java project为例,建立名为hibernate的项目。
★解压hibernate-3.2.0,导入hibernate-3.2的lib文件夹下的所有jar包
★ 导入MySQL驱动jar包mysql-connector-java-5.1.20-bin.jar
这里假设项目中只需用一个实体User
User.java
package com.danny.po;
public class User {
private String id;
private String name;
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
在跟实体类User.java相同目录下建立User.hbm.xml文件
User.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping SYSTEM "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="org.hibernate.test.exception" >
<class name="com.danny.po.User">
<id name="id">
<generator class="uuid"/>
</id>
<property name="name"/>
<property name="password"/>
</class>
</hibernate-mapping>
在src文件夹下建立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 name="foo">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.24.179:3306/hibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="com/danny/po/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
由于每种数据库的sql语言多少会有所差异,所以需要在这里设置hibernate的数据库方言。配置文件中,名为hibernate.dialect的属性中,将hibernate的数据库方言设置为mysql方言。这里可以简单理解方言跟设计模式中的适配器模式差不多~~只要这里设置了方言,无论hibernate操作何种数据库,最终都会自动转换为相对应数据库的sql语言。
如果将hibernate.show_sql属性值设置为true,在hibernate执行操作的时候,会将所转化并执行的sql语句打印到控制台,便于跟踪调试。
mapping resource=”com/danny/po/User.hbm.xml” 表示添加一个实体映射。这里只添加User实体映射。
关于hibernate.cfg.xml更多详细的属性,可以参考hibernate-3.2\etc\下的hibernate.properties文件。
至此,一个简单的Hibernate环境就基本搭建好了。
【 原创不易,转载请注明出处——胡玉洋《【SSH快速进阶】——Hibernate环境搭建》】