主题:Hibernate入门之自己写的小例子的总结(转自vatful)

转载自javaeye的vatful

俺是新学Hibernate的,望大家不要见笑。 

本机环境介绍: 
JB7.0 
hibernate-2.0.3 
Oracle8.1客户端 

数据库: 
局域网内的服务器上的Oracle8.1 
服务器IP地址:x.x.x.x 
端口:1521 
数据库名:OraHib 
(请保证以上数据库信息已建好,并获得操作数据库的登录名和密码) 

开始编程: 
(1)用JB新建一个工程,如hiberante_demo2, 


(2)为你的工程添加Required Libraries(Project->Project Properties->Paths->Required Libraries):添加hibernate-2.0.3目录中lib目录下的所有jar,添加hibernate-2.0.3根目录下hibernate2.jar,添加本地Oracle8.1目录中jdbc目录下的lib子目录中的classes12.zip(这里有连接数据库时需要的驱动oracle.jdbc.driver.OracleDriver)。 

------------------------ 
2004.3.11 15:23 补充: 
运行此程序时,有不少朋友碰到log4j报错的问题,建议大家留心classpath中是否有log4j的包, 
如果有这个包 
#可以在classpath中把它删除 
#也可以本例子第四步做完后复制log4j的prop文件(路径是:hibernate目录\src\log4j.properties)到工程的classes子目录下。 

感谢maxpain,zxyfd2000提出这个问题。 
------------------------ 

(3)新建一个Class,包是person,类名是PersonModel,它有三个成员变量分别是id,name,address(对应于数据库表中的三个字段。咦,表还没有阿!没关系,后边的程序会利用hibernate自动生成表,不需要自己再去操作数据库建表,真是太省事了,),类中还需要三个成员变量的get,set方法,代码结果如下: 

[code="java"] 
package person; 

import java.io.Serializable; 

public class PersonModel implements Serializable { 
private Long id; 
private String name; 
private String address; 
public Long getId() { 
return id; 
} 
public void setId(Long id) { 
this.id = id; 
} 
public void setName(String name) { 
this.name = name; 
} 
public String getName() { 
return name; 
} 
public void setAddress(String address) { 
this.address = address; 
} 
public String getAddress() { 
return address; 
} 

} 
[/code] 

 

上边做好了person.PersonModel类,我请各位看官注意一点,不是说可以自动生成表吗?是啊!那岂不是表中字段想怎么定义就怎么定义了啊?Yeah,完全正确。是不是觉得很自由啊! 

俺这个测试,主要是想对表进行插入和查询操作,并且这个表只有一个主键(这里就是id)!还有,后边还要写配置文件 PersonModel.hbm.xml (名称格式就是类名.hbm.xml,和类中内容完全对应,设置与数据库表之间的联系),因为这个测试中写的PersonModel.hbm.xml 非常简单,主键是用oracle数据库自动生成的,是整型的数据,写类时这个id我定义为long型了。你如果想用其他类型的主键,看看其他的文章吧。 

(4)编译person.PersonModel类,然后把hibernate-2.0.3目录中src子目录下的hibernate.properties文件拷贝到hiberante_demo2这个工程目录中的classes子目录下。 

(5)修改hibernate.properties中的数据源连接,在文件中找到如下所示的HypersonicSQL数据源连接的位置,这是默认的数据源连接。 
[code="java"] 
## HypersonicSQL 

hibernate.dialect net.sf.hibernate.dialect.HSQLDialect 
hibernate.connection.driver_class org.hsqldb.jdbcDriver 
hibernate.connection.username sa 
hibernate.connection.password 
#hibernate.connection.url jdbc:hsqldb:hsql://localhost 
hibernate.connection.url jdbc:hsqldb:test 
[/code] 

六行中第五行已经注释掉了,现在把其他五行也注释掉。 
结果如下 
[code="java"] 
## HypersonicSQL 

#hibernate.dialect net.sf.hibernate.dialect.HSQLDialect 
#hibernate.connection.driver_class org.hsqldb.jdbcDriver 
#hibernate.connection.username sa 
#hibernate.connection.password 
#hibernate.connection.url jdbc:hsqldb:hsql://localhost 
#hibernate.connection.url jdbc:hsqldb:test 
[/code] 

再找到 
[code="java"] 
## Oracle 

#hibernate.dialect net.sf.hibernate.dialect.OracleDialect 
#hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver 
#hibernate.connection.username ora 
#hibernate.connection.password ora 
#hibernate.connection.url jdbc:oracle:thin:@localhost:1521:test 
[/code] 
这是Oracle数据源连接 

去掉注释,修改为 
[code="java"] 
## Oracle 

hibernate.dialect net.sf.hibernate.dialect.OracleDialect 
hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver 
hibernate.connection.username your_database_username 
hibernate.connection.password your_database_password 
hibernate.connection.url jdbc:oracle:thin:@x.x.x.x:1521:OraHib 
[/code] 
oracle.jdbc.driver.OracleDriver,因为这个类,所以开始要把class12.zip加进来。下边很好懂,数据库的登录名,密码,x.x.x.x 为数据库所在服务器的ip地址,1521是端口,OraHib是数据库名。 

(6)在PersonModel.class所在的目录中新建PersonModel.hbm.xml,其内容如下: 
[code="java"] 
 
 
<hibernate-mapping> 

<class name="person.PersonModel" table="ZY_PERSON"> 

 
<id name="id" type="long"> 
<generator class="sequence"> 
ZY_PERSON_ID_SEQ 
</generator> 
</id> 

<property name="name"> 
<property name="address"> 

</class> 
</hibernate-mapping> 
[/code] 

简单解释 
<class name="person.PersonModel" table="ZY_PERSON"> 
PersonModel这个类对应数据库中ZY_PERSON这个表(现在还没有,后边自动生成) 

<id name="id" type="long"> 
<generator class="sequence"> 
ZY_PERSON_ID_SEQ 
</generator> 
</id> 
name="id" 这是类中的id,这里定义它为主键用<id></id>标记,类型为long型,主键用class="sequence"这种形式生成(这适合oracle数据库),ZY_PERSON_ID_SEQ是在oracle数据库中对应的sequence的名称(这个sequence,程序也将自动产生)。 

<property name="name"> 
<property name="address"> 
另外的两个成员变量。 

以上是非常简单的配置方式,数据库中的ZY_PERSON将有三个字段,名字与类中的一样,name, address 都将是String型。数据库中字段可以和类中的名称不一样,请参考其他的文章。 

配置都完成了,剩下的工作就是编写测试代码测试hibernate了。 
再休息一会儿。

 

(7)最后一步了, 

在hiberante_demo2工程根目录下新建一个sql_out_lib文件夹。 
在JB中新建一个类,包是person,类名TestPersonModel,输入代码,结果如下: 
[code="java"] 
package person; 

import net.sf.hibernate.SessionFactory; 
import net.sf.hibernate.cfg.Configuration; 
import net.sf.hibernate.tool.hbm2ddl.SchemaExport; 



public class TestPersonModel { 
private static SessionFactory sessionFactory; 
public static void main(String[] args) throws Exception{ 
Configuration conf= new Configuration().addClass(PersonModel.class); 

//第一次运行时用来在数据库中创建表 
//并且把sql语句输出到txt文件用的 
//以后的运行要去掉这一段,否则每次都新建表 

SchemaExport dbExport=new SchemaExport(conf); 
dbExport.setOutputFile("sql_out_lib\\sql.txt"); 
dbExport.create(true, true); 



} 
} 
[/code] 
我们已新建了sql_out_lib目录,这里通过SchemaExport 设置一个附加的输出文件,把hibernate生成的sql语句输出一份到sql.txt(这个文件名可随便定义),然后执行create操作。这时候数据库中就建好了ZY_PERSON表和ZY_PERSON_ID_SEQ。 

在JB中再新建一个类,包是person,类名TestPersonModel2,输入代码,结果如下: 
[code="java"] 
package person; 

import net.sf.hibernate.Session; 
import net.sf.hibernate.Transaction; 
import net.sf.hibernate.SessionFactory; 
import net.sf.hibernate.cfg.Configuration; 




public class TestPersonModel2 { 
private static SessionFactory sessionFactory; 
public static void main(String[] args) throws Exception{ 
Configuration conf= new Configuration().addClass(PersonModel.class); 




//在表中插入第一条数据 

sessionFactory = conf.buildSessionFactory(); 
Session s = sessionFactory.openSession(); 

Transaction t = s.beginTransaction(); 

PersonModel p1=new PersonModel(); 
p1.setName("robin"); 
p1.setAddress("上海"); 

//2.持久化 
s.save(p1); 
//此时p1已经可以在数据库中找到 
t.commit(); 

s.close(); 


} 
} 
[/code] 
这跟用jdbc连数据库一样,Session 相当于connection,Transaction 是事务处理,PersonModel p1不需设id,数据库自动生成。 

在JB中再新建一个类,包是person,类名TestPersonModel3,输入代码,结果如下: 
[code="java"] 
package person; 

import net.sf.hibernate.Session; 
import net.sf.hibernate.SessionFactory; 
import net.sf.hibernate.cfg.Configuration; 
import net.sf.hibernate.Query; 

public class TestPersonModel3 { 
private static SessionFactory sessionFactory; 
public static void main(String[] args) throws Exception{ 
Configuration conf= new Configuration().addClass(PersonModel.class); 

sessionFactory = conf.buildSessionFactory(); 
Session s = sessionFactory.openSession(); 
PersonModel p = new PersonModel(); 
Query q = s.createQuery("from PersonModel as p where p.id=1"); 
p = (PersonModel) q.list().get(0); 
System.out.println(p.getName()); 
s.close(); 
} 
} 
[/code] 
注意查询语句的写法,查PersonModel类(就是查ZY_PERSON表),起个别名叫小p,where语句查小p的id等于1;q.list()返回List类,再用get(int) 
方法get(0)取第一个结果,我们的查询结果出来了。 

结束了 :!: 

 

初学hibernate不得不提的可能碰到的几个问题 

(1)*.hbm.xml文件中主键的定义不要弄错了,要选择合适的主键生成方式,错用过<generator class="identity">。 

(2)自己写例子时,也从网上拷贝代码下来。class编译无法通过,运行时xml文件中有无法识别的字符,都可能是因为拷贝的代码中有看不见的不合格式的字符,如果有问题仔细检查一下。 

(3)最大的一个错误,开始做测试时,creat语句,插入语句都执行成功,可是查询语句如何也成功不了,郁闷了好几天,后来还有其他兄弟也遇到同样问题,还问我这个菜鸟,我如之奈何?我要rapidSQL访问数据库creat语句,插入语句,查询语句都可以,说明数据库那边没有任何问题,这边creat语句,插入语句都可以,说明代码没问题,单单一个查询语句出怪子。实在没辙,问了一些高手也没有答复,于是放下了。一次偶然的机会,让我碰到oracle.jdbc.driver.OracleDriver的版本问题,于是想到这儿,原来第一次连接的数据库是Oracle9,版本太高了。 
仅以此鉴与大家共享。 

 更新数据库

更新 
[code="java"]package person; 

import net.sf.hibernate.Session; 
import net.sf.hibernate.Transaction; 
import net.sf.hibernate.SessionFactory; 
import net.sf.hibernate.cfg.Configuration; 
import net.sf.hibernate.Query; 

public class TestPersonModel4 { 
private static SessionFactory sessionFactory; 
public static void main(String[] args) throws Exception{ 
Configuration conf= new Configuration().addClass(PersonModel.class); 

sessionFactory = conf.buildSessionFactory(); 
Session s = sessionFactory.openSession(); 
Transaction t = s.beginTransaction(); 
PersonModel p = new PersonModel(); 
Query q = s.createQuery("from PersonModel as p where p.id=1"); 
p = (PersonModel) q.list().get(0); 
System.out.println(p.getName()); 
p.setName(p.getName()+"二世"); 
t.commit(); 
s.close(); 
} 
}[/code] 

 

删除数据库

[code="java"]package person; 

import net.sf.hibernate.Session; 
import net.sf.hibernate.Transaction; 
import net.sf.hibernate.SessionFactory; 
import net.sf.hibernate.cfg.Configuration; 
import net.sf.hibernate.Query; 

public class TestPersonModel5 { 
private static SessionFactory sessionFactory; 
public static void main(String[] args) throws Exception{ 
Configuration conf= new Configuration().addClass(PersonModel.class); 

sessionFactory = conf.buildSessionFactory(); 
Session s = sessionFactory.openSession(); 
Transaction t = s.beginTransaction(); 
PersonModel p = new PersonModel(); 
Query q = s.createQuery("from PersonModel as p where p.id=1"); 
p = (PersonModel) q.list().get(0); 
System.out.println(p.getName()); 
s.delete(p); 
t.commit(); 
s.close(); 
} 
}[/code] 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值