Hibernate的第一个例子

第一步:创建一个实体

注意:不要使用构造方法,否则会有错误

package com.itany.bean;

import java.util.Date;

public class User{

private int id;
private String name;
private Date birthday;
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 Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}

}

 

第二步:创建映射文件User.hbm.xml

注意:1.该文件以.hbm.xml结尾,加上相应的的实体类的类名

   2.改文件与其对应的实体放在同一包下

<?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 package="com.itany.bean">

<class name="User" >
<!--相当于表的主键-->
<id name="id">
<generator class="native"/>
</id>

<!--表的其他字段-->
<property name="name"/>
<property name="birthday"/>
</class>

</hibernate-mapping>

 

第三步:创建hibernate.cfg.xml

注意:1.默认就使用这个名称,如果要换名称,要再使用的时候初始化自己想用的名称

   2.文件放在src目录下

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<!-- 注意:1.要先建立相应的database
2.要加载jar包,包括数据库驱动包
3.遇到特殊字符如&要替换 -->
<session-factory>

<!-- 建立链接 -->
<property name="connection.url">
jdbc:mysql://127.0.0.1:3306/hibernate?useUnicode=true&amp;characterEncoding=utf8
</property>

<!-- 使用方言 -->
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect</property>

<!-- 加载驱动 -->
<property name="connection.driver_class">
com.mysql.jdbc.Driver</property>

<!-- 设置用户名 -->
<property name="connection.username">root</property>

<!-- 设置密码 -->
<property name="connection.password">20140401</property>

<!-- 输出sql语句到控制台 -->
<property name="show_sql">true</property>
<mapping resource="com/itany/bean/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>

第四步:测试建表

注意:使用MySQL时要先建好数据库

package com.itany.bean;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class CreateTable {

public static void main(String[] args) {
//根据hibernate.cfg.xml文件生成相应的Configuration对象
Configuration cfg=new Configuration().configure();
//使用适配器模式通过Configuration获得SchemaExport
SchemaExport export=new SchemaExport(cfg);
//创建数据库表
export.create(true,true);
}
}

执行后控制台会输出建表语句

posted @ 2015-05-17 15:29  爱上咖啡的唐  阅读(166)  评论(0编辑  收藏  举报