最近在看关于Hibernate,可是刚刚入门就被配置问题卡住了,我在eclipse下怎么配置都不顺利
有那位仁兄玩过Hibernate的来指导一下喂~~
最好能有一个最最最最简单的例子,感激ing.....谢谢
最近在看关于Hibernate,可是刚刚入门就被配置问题卡住了,我在eclipse下怎么配置都不顺利
有那位仁兄玩过Hibernate的来指导一下喂~~
最好能有一个最最最最简单的例子,感激ing.....谢谢
关于Hibernate
是啊,那就由我们开始讨论吧
我先说说我这两天来学弄hibernate的经历
首先当然是准备软件啦
0.J2SE5.0平台 从www.java.com中下载废话...
1.eclipse 从www.eclipse.org里面找,最新的正式版本是3.11,但是我喜欢用3.2 :)
2.hibernate
3.mysql5.0 和 mysql-connector-java-3.1.11从www.mysql.com里面找,5.0和3.1.11也是最新的版本
4.mysql-front 3.2 从http://www.happydown.com/soft/down.asp?id=4087&no=1可以下载到他的破解版本(这个不是官方的站点,可能有病毒,所以下完后请仔细杀毒和检查)
安装好eclipse和mysql5.0
我们的目标是建立一个应用程序,并且利用hibernate连接到数据库,执行插入和读取操作
1.建立一个sample数据库和t_user表
用mysql-front建立是相当的方便,不过这里为了简洁还是用命令好点
1.1建立sample数据库
DROP DATABASE IF EXISTS `sample`;
CREATE DATABASE `sample`;
USE `sample`;
1.2在sample中建立表t_user
CREATE TABLE `t_user` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(100) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
2.创建我们的项目
2.1创建工程
2.1.1在eclipse中新建立一个java应用项目HibernateSample
2.1.2建立net.sonofreedom.ompc.hibernate包
2.1.3导入外部jar,因为我是初学者,不知道那些包是必要的,那些是不必要的,也懒得一个个去调试,所以就all of them
(a) mysql-connector-java-
(b) hibernate3.jar
(c) 在hibernate解压包下有个lib目录,把他里面的jar全部加载!!
2.2配置工程的Hibernate,这里是关键,也是最容易出错的地方,注意所有的XML。
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=info, stdout
#log4j.logger.org.hibernate=info
log4j.logger.org.hibernate=debug
### log HQL query parser activity
#log4j.logger.org.hibernate.hql.ast.AST=debug
### log just the SQL
#log4j.logger.org.hibernate.SQL=debug
### log JDBC bind parameters ###
##log4j.logger.org.hibernate.type=info
#log4j.logger.org.hibernate.type=debug
### log schema export/update ###
##log4j.logger.org.hibernate.tool.hbm2ddl=debug
### log HQL parse trees
#log4j.logger.org.hibernate.hql=debug
### log cache activity ###
#log4j.logger.org.hibernate.cache=debug
### log transaction activity
#log4j.logger.org.hibernate.transaction=debug
### log JDBC resource acquisition
#log4j.logger.org.hibernate.jdbc=debug
### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
<?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="hibernate.connection.url">
jdbc:mysql://localhost/sample
</property>
<property name="hibernate.connection.driver_class">
org.gjt.mm.mysql.Driver
</property>
<property name="hibernate.connection.username">
yourroot
</property>
<property name="hibernate.connection.password">
yourpassword
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.show_sql">
True
</property>
<property name="hibernate.use_outer_join">
True
</property>
<property name="hibernate.transaction.factory_class">
org.hibernate.transaction.JDBCTransactionFactory
</property>
<mapping resource="net/sonofreedom/ompc/hibernate/Tuser.hbm.xml"/>
</session-factory>
</hibernate-configuration>
内容如下: 在这里我曾经碰到了大钉子,因为我的疏忽,错把hibernate.cfg.xml的xml头打到了这个文件中来,结果配置了2天都没发现这个错误~~大家一定不要像我那么傻!
<?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="net.sonofreedom.ompc.hibernate.Tuser" table="t_user">
<id name="id" type="java.lang.Integer" column="id" unsaved-value="0">
<generator class="identity"/>
</id>
<property name="name" type="java.lang.String" column="name" not-null="true" length="100"/>
</class>
</hibernate-mapping>
2.3配置完毕,开始写代码
//Tuser.java
package net.sonofreedom.ompc.hibernate;
import java.io.Serializable;
public class Tuser implements Serializable{
private static final long serialVersionUID =
private Integer id;
private String name;
public Tuser(String name){
this.name = name;
}
public Tuser(){
//
}
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 String toString(){
return "id="+id+"\tname="+name;
}
}
//HibernateTest.java
package net.sonofreedom.ompc.hibernate;
import junit.framework.TestCase;
import junit.framework.Assert;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import java.util.List;
import net.sonofreedom.ompc.hibernate.Tuser;
public class HibernateTest extends TestCase {
Session session = null;
protected void setUp() {
try {
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
session = sessionFactory.openSession();
} catch (HibernateException he) {
he.printStackTrace();
}
}
protected void tearDown() {
try {
session.close();
} catch (HibernateException he) {
he.printStackTrace();
}
}
public void testInsert() {
Transaction tran = null;
try {
tran = session.beginTransaction();
Tuser user = new Tuser();
user.setName("神vlinux飘飘");
session.save(user);
session.flush();
tran.commit();
Assert.assertEquals(user.getId().intValue() > 0, true);
} catch (HibernateException he) {
he.printStackTrace();
Assert.fail(he.getMessage());
if (tran != null) {
try {
tran.rollback();
} catch (HibernateException he1) {
he1.printStackTrace();
}
}
}
}
public void testSelect() {
String hql = " from Tuser where name='vlinux'";
try {
List userList = session.createQuery(hql).list();
Tuser user = (Tuser) userList.get(0);
Assert.assertEquals(user.getName(), "vlinux");
} catch (HibernateException he) {
he.printStackTrace();
Assert.fail(he.getMessage());
}
}
}
3最后,一切都OK了
我们从JUnit中运行这个HibernateTest.java
然后查看一下你的数据库,你发现了什么?
我知道,光光是文字不能够说明这些问题,下面我把我的代码打包发上来,而且把一些关键的配置界面截图给大家看
恩,写的很详细
但是如果作为一篇教材的话,注释有点少