01hibernate_first
第一个hibernate项目
1、新建java项目
2、创建User Library,加入如下jar
* HIBERNATE_HOME/hibernate3.jar
* HIBERNATE_HOME/lib/*.jar
* MySql jdbc驱动
3、创建hibernate配置文件hibernate.cfg.xml,为了便于调试最好加入log4j配置文件
4、定义实体类User.java
5、定义User类的映射文件User.hbm.xml
6、将User.hbml.xml文件加入到hibernate.cfg.xml文件中
7、编写hbm2ddl工具类,将实体类生成数据库表
a)
//读取hibernate.cfg.xml文件
Configuration cfg = new Configuration().configure();
SchemaExport export = new SchemaExport(cfg);
export.create(true, true);
b)drop table if exists User
15:04:53,062 WARN JDBCExceptionReporter:48 - SQL Warning: 1051, SQLState: 42S02
15:04:53,062 WARN JDBCExceptionReporter:49 - Unknown table 'user'
create table User (id varchar(255) not null, name varchar(255), password varchar(255), createTime datetime, expireTime datetime, primary key (id))
15:04:53,140 WARN JDBCExceptionReporter:48 - SQL Warning: 1051, SQLState: 42S02
15:04:53,140 WARN JDBCExceptionReporter:49 - Unknown table 'user'
8、开发客户端Client.java
a)public class Client {
public static void main(String[] args) {
//读取hibernate.cfg.xml文件
Configuration cfg = new Configuration().configure();
//创建SessionFactory
SessionFactory factory = cfg.buildSessionFactory();
Session session = null;
try {
session = factory.openSession();
//开启事务
session.beginTransaction();
User user = new User();
user.setName("白龙马");
user.setPassword("123");
user.setCreateTime(new Date());
user.setExpireTime(new Date());
//保存数据
session.save(user);
//提交事务
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
//回滚事务
session.getTransaction().rollback();
}finally {
if (session != null) {
if (session.isOpen()) {
//关闭session
session.close();
}
}
}
}
}
b)Hibernate: insert into User (name, password, createTime, expireTime, id) values (?, ?, ?, ?, ?)
c)
mysql> use 01_hibernate_first;
Database changed
mysql> show tables;
+------------------------------+
| Tables_in_01_hibernate_first |
+------------------------------+
| user |
+------------------------------+
1 row in set (0.00 sec)
mysql> select * from user;
+----------------------------------+--------+----------+---------------------+---------------------+
| id | name | password | createTime | expireTime |
+----------------------------------+--------+----------+---------------------+---------------------+
| 402881e538dbdbd80138dbdbda690001 | 白龙马 | 123 | 2012-07-31 15:06:54 | 2012-07-31 15:06:54 |
+----------------------------------+--------+----------+---------------------+---------------------+
1 row in set (0.00 sec)
为了方便跟踪sql执行,在hibernate.cfg.xml文件中加入:
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>