日期:2014-05-16 浏览次数:20397 次
虽然hibernate3.2版本已经很旧了,但是为了适应某些场合的应用和了解下hibernate,来学习一下3.2版本!
1:添加hibernate的jar文件:
?????????? hibernate根目录下面的:hibernate3.jar;
?????????? hibernate/lib下面的全部jar文件;
2:手动copy,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> <!-- hibernate连接的url --> <property name="hibernate.connection.url">jdbc:mysql://localhost/hibernateTest</property> <!-- hibernate连接驱动 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 数据库名字 --> <property name="hibernate.connection.username">root</property> <!-- 数据库密码 --> <property name="hibernate.connection.password">mysql</property> <!-- 数据库方言 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 输出sql语句 --> <property name="show_sql">true</property> <!-- 找到实体类的文件 --> <mapping resource="cn/keith/hibernate/model/User.hbm.xml" /> </session-factory> </hibernate-configuration>
??
3:建立实体类,里面有user的属性,并给出set(),get()方法:
user.java:
package cn.keith.hibernate.model; public class User { private String id; private String username; private String sex; private String mail; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getMail() { return mail; } public void setMail(String mail) { this.mail = mail; } }
?4:创建实体类相应的XXX.hbm.xml文件:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <!-- 默认的表面会与实体类名相同 --> <class name="cn.keith.hibernate.model.User" > <!-- 设置主键,uuid不唯一 --> <id name="id"> <generator class="uuid" /> </id> <!-- 表里属性,默认的与表同名,也可修改用到column=""属性 --> <property name="username" /> <property name="sex" /> <property name="mail" /> </class> </hibernate-mapping>
?5:写测试类:TestDB.java:
package cn.keith.hibernate.model; import org.hibernate.cfg.Configuration; import org.hibernate.tool.hbm2ddl.SchemaExport; public class TestDB { public static void main(String[] args) { // 读取hibernate配置文件 Configuration cfg = new Configuration().configure(); //将实体类转换为DDL语言,创建表 SchemaExport export = new SchemaExport(cfg); export.create(true, true); } }
?
如果Configuration cfg = new Configuration();会报:
Exception in thread "main" org.hibernate.HibernateException: The dialect was not set. Set the property hibernate.dialect.
?
错误!
?
*:数据库得自己创建,将配置在hibernate.cfg.xml的
<property name="hibernate.connection.url">jdbc:mysql://localhost/hibernateTest</property>
?
里!
?