Hibernate技术解说
Hibernate技术解说
1、 撰写数据库的定义
hibernate需要底层数据库的支持。我们为了测试也要求先建立数据库的相关表格,然后插入一些常用的数据来测试。
数据库的定义如下:
drop table TOY;
drop table CHILD;
drop table employers;
drop table employment_periods;
drop table employees;
create table CHILD (
ID NUMBER not null primary key
);
create table TOY (
TOY_ID NUMBER not null primary key,
CHILD_ID NUMBER ,
POSN NUMBER default 0,
NAME varchar(20) default '',
constraint FK_CHILD foreign key (CHILD_ID) references CHILD (ID)
);
DROP SEQUENCE SEQ_TOY;
DROP SEQUENCE SEQ_CHILD;
CREATE SEQUENCE "SEQ_TOY" INCREMENT BY 1 START WITH 1 MAXVALUE 1.0E28 MINVALUE 1 NOCYCLE CACHE 20 NOORDER;
CREATE SEQUENCE "SEQ_CHILD" INCREMENT BY 1 START WITH 1 MAXVALUE 1.0E28 MINVALUE 1 NOCYCLE CACHE 20 NOORDER;
主要做了这些工作:申明主键,申明外键,创建主键对应的sequence,注意我们采用的是oracle数据库。
2、 好了,我们可以写一个ant脚本来编译我们的程序了
主要的target如下:
定义环境变量:
<path id="myclasspath">
<fileset dir="${lib}">
<include name="*.jar"/>
<include name="*.zip"/>
</fileset>
<pathelement location="${build}"/>
</path>
编译:
<target name="compile" depends="init">
<echo message="compiling..." />
<javac srcdir="${src}" destdir="${build}" classpathref="myclasspath"/>
<copy todir="${build}" />
</target>
3、 好了,我们现在可以使用我们的hibernate了。
例如我们插入一个Child,写了一个函数如下:
public int insertChild(Child c) throws HibernateException {
Transaction tx = null;
Session s = null;
try{
s = HibernateSessionFactory.openSession();
tx = s.beginTransaction();
s.save(c);
tx.commit();
}catch(HibernateException he){
if ( tx!=null ){
tx.rollback();
}
throw he;
}finally{
s.close();
}
return c.getId();
}
关键部分用红色标出。实际上我们调用了session类的save方法,session类还有很多其他的方法可以调用,如下:update,load,delete等等。传入一个类的引用,便可以保存了。作用类似于insert into …,然后我们的测试代码如下:
//首先实例化三个Toy类
Toy t1 = new Toy();
t1.setName("wawa1");
Toy t2 = new Toy();
t2.setName("wawa2");
Toy t3 = new Toy();
t3.setName("wawa3");
Toy[] toys1 = new Toy[] {t1,t2};
Toy[] toys2 = new Toy[] {t1,t2,t3};
Toy[] toys3 = new Toy[] {t1,t2};
Child c = new Child();
c.setToys(toys1);
ed.insert(c);//插入含有两个toy的Child
c = (Child)ed.findById(c.getClass(),1);//从数据库中取得这个Child类
this.assertEquals(2,c.getToys().length);//应该是两个toy
c.setToys(toys2);//重新设置toys属性
ed.update(c);//更新到数据库中
使用单元测试结果如下:
compile:
[echo] compiling...
test:
[echo] run test...
[java] .15:13:21,818 INFO Environment:378 - Hibernate 2.0 beta 6
[java] 15:13:21,878 INFO Environment:412 - loaded properties from resource hibernate.properties: {hibernate.connection.driver_class=oracle.jdbc.driver.OracleDriver, hibernate.cglib.use_reflection_optimizer=true, hibernate.dialect=net.sf.hibernate.dialect.OracleDialect, hibernate.jdbc.use_streams_for_binary=true, hibernate.jdbc.batch_size=0, hibernate.query.substitutions=true 1, false 0, yes 'Y', no 'N', hibernate.query.imports=net.sf.hibernate.test, net.sf.hibernate.eg, hibernate.connection.username=zhaocw, hibernate.connection.url=jdbc:oracle:thin:@CCSERVER:1521:oracle8i, hibernate.show_sql=true, hibernate.connection.password=zhaocw, hibernate.statement_cache.size=25, hibernate.connection.pool_size=10}
[java] 15:13:21,898 INFO Environment:426 - using java.io streams to persist binary types
[java] 15:13:21,898 INFO Environment:427 - using CGLIB reflection optimizer
[java] 15:13:21,928 INFO Environment:437 - JVM proxy support: true
[java] 15:13:21,938 INFO Configuration:689 - Configuration resource: /hibernate.cfg.xml
[java] 15:13:22,929 INFO Configuration:270 - Mapping resource: hibernate/Child.hbm.xml
[java] 15:13:23,170 INFO Collection:174 - Mapping class: hibernate.Child -> CHILD
[java] 15:13:23,340 INFO Configuration:270 - Mapping resource: hibernate/Toy.hbm.xml
[java] 15:13:23,420 INFO Collection:174 - Mapping class: hibernate.Toy -> TOY
[java] 15:13:24,411 INFO Configuration:871 - Configured SessionFactory: null
[java] 15:13:24,411 INFO Collection:976 - Mapping collection: hibernate.Child.toys -> TOY
[java] 15:13:25,242 INFO SessionFactoryImpl:140 - building session factory
[java] 15:13:25,262 INFO Dialect:37 - Using dialect: net.sf.hibernate.dialect.OracleDialect
[java] 15:13:25,272 INFO DriverManagerConnectionProvider:41 - Hibernate connection pool size: 10
[java] 15:13:25,292 INFO DriverManagerConnectionProvider:70 - using driver: oracle.jdbc.driver.OracleDriver at URL: jdbc:oracle:thin:@CCSERVER:1521:oracle8i
[java] 15:13:25,292 INFO DriverManagerConnectionProvider:71 - connection properties: {user=zhaocw, password=zhaocw}
[java] 15:13:25,323 INFO PreparedStatementCache:60 - prepared statement cache size: 25
[java] 15:13:25,333 INFO SessionFactoryImpl:170 - Use outer join fetching: true
[java] 15:13:26,033 INFO SessionFactoryImpl:193 - Use scrollable result sets: true
[java] 15:13:26,033 INFO SessionFactoryImpl:202 - echoing all SQL to stdout
[java] 15:13:27,145 INFO SessionFactoryObjectFactory:82 - no JDNI name configured
[java] 15:13:27,145 INFO SessionFactoryImpl:287 - Query language substitutions: {no='N', true=1, yes='Y', false=0}
[java] Hibernate: select SEQ_CHILD.nextval from dual
[java] Hibernate: select SEQ_TOY.nextval from dual
[java] Hibernate: select SEQ_TOY.nextval from dual
[java] Hibernate: insert into CHILD (id) values (?)
[java] Hibernate: insert into TOY (name, TOY_ID) values (?, ?)
[java] Hibernate: update TOY set CHILD_ID=?, POSN=? where TOY_ID=?
[java] Hibernate: select child0_.id as id from CHILD child0_ where child0_.id=?
[java] Hibernate: select toy0_.TOY_ID as TOY_ID__, toy0_.POSN as POSN__, toy0_.TOY_ID as TOY_ID, toy0_.name as name from TOY toy0_ where toy0_.CHILD_ID=?
[java] Hibernate: select SEQ_TOY.nextval from dual
[java] Hibernate: insert into TOY (name, TOY_ID) values (?, ?)
[java] Hibernate: update TOY set name=? where TOY_ID=?
[java] Hibernate: update TOY set CHILD_ID=null, POSN=null where CHILD_ID=?
[java] Hibernate: update TOY set CHILD_ID=?, POSN=? where TOY_ID=?
[java] Hibernate: select child0_.id as id from CHILD child0_ where child0_.id=?
[java] Hibernate: select toy0_.TOY_ID as TOY_ID__, toy0_.POSN as POSN__, toy0_.TOY_ID as TOY_ID, toy0_.name as name from TOY toy0_ where toy0_.CHILD_ID=?
[java] Hibernate: delete from TOY where TOY_ID=?
[java] Hibernate: update TOY set name=? where TOY_ID=?
[java] Hibernate: update TOY set CHILD_ID=null, POSN=null where CHILD_ID=?
[java] Hibernate: update TOY set CHILD_ID=?, POSN=? where TOY_ID=?
[java] Time: 6.269
[java] OK (1 test)
可以看见实际上hibernate执行的sql语句,测试结果是成功的。
五、总结
实际上,Hibernate可以实现多层次继承的架构,经常用到的包括<many-to-one>,<one-to-many>,<one-to-one>,<subclass>,<joined-subclass>等等。还有组件功能<component>可以让某个属性类存储在父类中。总之,Hibernate功能十分强大,效率也非常搞。建议大家在使用的过程中不断的总结经验,最好能够分享自己的经验。
相关连接:
hibernate论坛:http://sourceforge.net/forum/forum.php?forum_id=128638
hibernate主页:http://hibernate.sourceforge.net
FAQ: http://hibernate.bluemars.net/14.html?cowiki=c39f9c2408fc3b0ae5d9eeadd0953905#9