一个简单的Hibernate例子的心得
今天看了一下12*给我的那个Hibernate的简单实例,结果弄了一个下午才搞定.有点感想和大家分享一下下. 稍后会把程序贴出来给大家展示一下出错地方.
1.开发环境eclipse3.2.1,mysql5.0
2, 首先是开发环境配置上,我最开始的时候是把Hibernate所需的jar导入到window--refrences-java-installed jar中,结果编译好多次也不行,后来我就把jar全部删除了,在我建的项目上
单击右键,选择Properties-java build path中,选择add external jars,将需要的jar加入即可
3,上面完成后我执行程序发现数据不能插入到数据库,但是能够显示插入的sql语句,并且可以从数据库取出数据,试了一下才发现原因是建表的时候没有把主键ID设置为自动增加,致使无法插入,原因是我在xml文件中配置的主键的时候使用了这个<generator class="identity"/>,而他所对应的数据库主键必须是自动增加的 ,这只是我理解的,因为实在找不出其他原因了^_^.
收获就这么点,还是给大家看看代码吧:
所需jar文件:
antlr.jar
cglib.jar
asm.jar
asm-attrs.jar
common-collections.jar
common-logging.jar
ehcache.jar
hibernate3.jar
jta.jar
dom4j.jar
log4j.jar
mysql初始化语句:
# MySQL-Front 3.1 (Build 9.0)
# Host: localhost Database: demo
# ------------------------------------------------------
# Server version 5.0.22-community-nt
#
# Table structure for table user
#
CREATE TABLE `user` (
`id` int(6) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`age` int(6) NOT NULL default '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;
#
# Dumping data for table user
#
INSERT INTO `user` VALUES (1,'david',23);
INSERT INTO `user` VALUES (2,'caterpillar',30);
INSERT INTO `user` VALUES (3,'caterpillar',30);
# MySQL-Front 3.1 (Build 9.0)
# Host: localhost Database: demo
# ------------------------------------------------------
# Server version 5.0.22-community-nt
#
# Table structure for table user
#
CREATE TABLE `user` (
`id` int(6) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`age` int(6) NOT NULL default '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;
#
# Dumping data for table user
#
INSERT INTO `user` VALUES (1,'david',23);
INSERT INTO `user` VALUES (2,'caterpillar',30);
INSERT INTO `user` VALUES (3,'caterpillar',30);
# MySQL-Front 3.1 (Build 9.0)
# Host: localhost Database: demo
# ------------------------------------------------------
# Server version 5.0.22-community-nt
#
# Table structure for table user
#
CREATE TABLE `user` (
`id` int(6) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`age` int(6) NOT NULL default '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;
#
# Dumping data for table user
#
INSERT INTO `user` VALUES (1,'david',23);
INSERT INTO `user` VALUES (2,'caterpillar',30);
INSERT INTO `user` VALUES (3,'caterpillar',30);
# MySQL-Front 3.1 (Build 9.0)
# Host: localhost Database: demo
# ------------------------------------------------------
# Server version 5.0.22-community-nt
#
# Table structure for table user
#
CREATE TABLE `user` (
`id` int(6) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`age` int(6) NOT NULL default '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;
#
# Dumping data for table user
#
INSERT INTO `user` VALUES (1,'david',23);
INSERT INTO `user` VALUES (2,'caterpillar',30);
INSERT INTO `user` VALUES (3,'caterpillar',30);
数据库配置文件:用户名和密码根据自己数据库设置的进行修改
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="show_sql">
true
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/demo
</property>
<property name="connection.username">
root
</property>
<property name="connection.password">
851120
</property>
<!-- 以下設置物件與資料庫表格映射文件 -->
<mapping resource="onlyfun/caterpillar/User.hbm.xml"/>
<mapping resource="events/Event.hbm.xml"/>
</session-factory>
</hibernate-configuration>
user表对应的类:
package onlyfun.caterpillar;
public class User {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
user对应的xml文件
User.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="onlyfun.caterpillar.User"
table="user">
<id name="id" column="id">
<generator class="identity"/>
</id>
<property name="name" column="name"/>
<property name="age" column="age"/>
</class>
</hibernate-mapping>
控制操作的接口:
package onlyfun.caterpillar;
public interface IUserDAO {
public void insert(User user);
public User find(Integer id);
}
接口实现
package onlyfun.caterpillar;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
public class UserDAO implements IUserDAO {
private SessionFactory sessionFactory;
public UserDAO() {
}
public UserDAO(SessionFactory sessionFactory) {
this.setSessionFactory(sessionFactory);
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void insert(User user) {
// 取得Session
Session session = sessionFactory.openSession();
// 开启事务
Transaction tx= session.beginTransaction();
// 直接储存对象
session.save(user);
// 送出事务
tx.commit();
session.close();
}
public User find(Integer id) {
Session session = sessionFactory.openSession();
User user = (User) session.get(User.class, id);
session.close();
return user;
}
}
测试类:
package onlyfun.caterpillar;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateDemo {
public static void main(String[] args) {
// Configuration 负责管理 Hibernate 配置讯息
Configuration config =
new Configuration().configure();
// 根据 config 建立 SessionFactory
// SessionFactory 将用于建立 Session
SessionFactory sessionFactory =
config.buildSessionFactory();
// 建立DAO对象
IUserDAO userDAO = new UserDAO(sessionFactory);
User user = new User();
user.setName("caterpillar");
user.setAge(30);
userDAO.insert(user);
user = userDAO.find(new Integer(1));
System.out.println("name: " + user.getName()+"----"+user.getAge()+"----"+user.getId());
}
}
到此为止