在Hibernate关联关系映射实例速查一文中通过myeclipse快速做出了Hibernate各种映射的示例时隔快一年了但是还是有博友向我索要工程源码很遗憾的是已经找不到了但找到一了一个测试代码对双向关联和乐观锁的测试其实映射类型很多搞清楚一对多基本上所有的映射就搞明白了一对一也是一对多的特例而已多对多也可以转换为一对多和多对一并且实际中很少用到多对多
还是老规矩因为是测试代码几乎全部是myeclipse生成的我稍作了修改并且应博友阿飞的留言我做了详细的注释
例子两部分
一对多双向映射模型是班级-学生模型两个实体分别是Tclass和Student
乐观锁的是使用版本分别使用递增整数和时间戳两个实体分别是Foo和Bar
Tclass实体及其映射
public class Tclass implements javaioSerializable {
// Fields
private Long cid;
private String cname;
private Set students = new HashSet();
// Constructors
// Property accessors
public String toString() {
return Tclass{ +
cid= + cid +
cname= + cname + \ +
};
}
}
<hibernatemapping>
<class name=stuonemanypojoTclass table=tclass>
<id name=cid type=javalangLong>
<column name=cid/>
<generator class=native/>
</id>
<property name=cname type=javalangString>
<column name=cname length= notnull=true/>
</property>
<! set元素属性说明
name=students 设置表示多个学生的变量名
inverse=true 关系控制反转不掌握主控权表示Tclass不控制与Student关联关系而是将这种关联控制的权利转给Student
cascade=all 表示级联操作操作班级的时候对班级关联的学生也做同样的操作
lazy=true 查询班级的时候延迟查询班级下的学生
>
<set name=students inverse=true cascade=all lazy=true>
<key>
<!
name=fk_cid 指定关联的外键列
notnull=true 说明这个外间列不能为空多余的
>
<column name=fk_cid notnull=true/>
</key>
<! 指定所关联的类 >
<onetomany class=stuonemanypojoStudent/>
</set>
</class>
</hibernatemapping>
Student实体及其映射
public class Student implements javaioSerializable {
// Fields
private Long sid;
private Tclass tclass;
private String sname;
// Constructors
// Property accessors
public String toString() {
return Student{ +
sid= + sid +
sname= + sname + \ +
};
}
}
<hibernatemapping>
<class name=stuonemanypojoStudent table=student>
<id name=sid type=javalangLong>
<column name=sid />
<generator class=native />
</id>
<! 表示多个Student关联一个Tclass >
<!
name=tclass 关联的成员变量名;
class=stuonemanypojoTclass 表示所关联的类;
fetch=select 查询策略有两个选项select和join
select表示通过外联接来进行查询查询速度稍慢但消耗资源少;
join表示通过内连接来查询速度快但消耗资源多
>
<manytoone name=tclass
class=stuonemanypojoTclass
fetch=select>
<! 指定关联的外键列 >
<column name=fk_cid notnull=true />
</manytoone>
<property name=sname type=javalangString>
<column name=sname length= notnull=true />
</property>
</class>
</hibernatemapping>
测试班级学生模型
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
testSave();
// testDeleteTclass();
}
public static void testSave() {
Tclass c = new Tclass();
csetCname(某班级);
Student s = new Student();
Student s = new Student();
ssetSname(张三);
ssetTclass(c);
ssetSname(李四);
ssetTclass(c);
cgetStudents()add(s);
cgetStudents()add(s);
Session session = HibernateSessionFactorygetSession();
Transaction tx = sessionbeginTransaction();
sessionsave(c);
mit();
sessionclose();
}
public static void testUpdateClass() {
Systemoutprintln(正在调用testUpdateClass());
Session session = HibernateSessionFactorygetSession();
Tclass c = (Tclass) sessionload(Tclassclass LongvalueOf(L));
Systemoutprintln(c);
csetCname(班级更名);
sessionbeginTransaction(mit();
}
public static void testUpdateStudent() {
Systemoutprintln(正在调用testUpdateStudent());
Session session = HibernateSessionFactorygetSession();
Tclass c = (Tclass) sessionload(Tclassclass LongvalueOf(L));
Student s = (Student) sessionload(Studentclass LongvalueOf(L));
ssetSname(学生改名换姓王八);
ssetTclass(c);
Systemoutprintln(c);
Systemoutprintln(s);
sessionbeginTransaction(mit();
Systemoutprintln(s);
Systemoutprintln(sgetTclass());
}
public static void testDeleteStudent() {
Systemoutprintln(正在调用testDelete());
Session session = HibernateSessionFactorygetSession();
Student s = (Student) sessionload(Studentclass LongvalueOf(L));
Systemoutprintln(s);
Systemoutprintln(sgetTclass());
sessiondelete(s);
sessionbeginTransaction(mit();
}
public static void testDeleteTclass() {
Systemoutprintln(正在调用testDelete());
Session session = HibernateSessionFactorygetSession();
Tclass c = (Tclass) sessionload(Tclassclass LongvalueOf(L));
Systemoutprintln(c);
sessiondelete(c);
sessionbeginTransaction(mit();
}
public static void testQueryClass() {
Systemoutprintln(正在调用testQueryClass());
Session session = HibernateSessionFactorygetSession();
Tclass c = (Tclass) sessionload(Tclassclass new Long());
Systemoutprintln(c);
Systemoutprintln(cgetStudents());
}
public static void testQueryStudent() {
Systemoutprintln(正在调用testQueryStudent());
Session session = HibernateSessionFactorygetSession();
Student s = (Student) sessionload(Studentclass new Long());
Systemoutprintln(s);
Systemoutprintln(sgetTclass());
}
}
下面是乐观锁的使用
基于整数的版本控制
Foo实体和映射文件
public class Foo implements javaioSerializable {
// Fields
private Long pid;
private Integer version;
private String name;
// Constructors
// Property accessors
public String toString() {
return Foo{ +
pid= + pid +
version= + version +
name= + name + \ +
};
}
}
<hibernatemapping>
<class name=stuonemanypojoFoo table=foo
optimisticlock=version>
<id name=pid type=javalangLong>
<column name=pid />
<generator class=native />
</id>
<! 版本控制字段必须在id后配置 >
<version name=version type=javalangInteger>
<column name=version />
</version>
<property name=name type=javalangString>
<column name=name length= notnull=true />
</property>
</class>
</hibernatemapping>
测试
public class TestFoo {
/**
* @param args
*/
public static void main(String[] args) {
testSave();
}
public static void testSave(){
Foo foo = new Foo(foo);
Session session = HibernateSessionFactorygetSession();
sessionsave(foo);
sessionbeginTransaction(mit();
sessionclose();
}
}
基于时间戳的版本控制
public class Bar implements javaioSerializable Comparable {
// Fields
private Long id;
private Date timestamp;
private String name;
// Constructors
// Property accessors
public String toString() {
return Bar{ +
id= + id +
timestamp= + timestamp +
name= + name + \ +
};
}
/**
* 排序接口方法实现为了能对查询结果按照id的大小进行排序
* @param o 排序对象
* @return 比较值
*/
public int compareTo(Object o) {
Bar bar = (Bar) o;
Long res = thisid bargetId();
return resintValue();
}
}
<hibernatemapping>
<class name=stuonemanypojoBar table=bar optimisticlock=version>
<id name=id type=javalangLong>
<column name=id />
<generator class=native />
</id>
<version name=timestamp type=javautilDate>
<column name=timestamp length= notnull=true />
</version>
<property name=name type=javalangString>
<column name=name length= notnull=true />
</property>
</class>
</hibernatemapping>
public class TestBar {
public static void main(String args[]) {
testUpdateBar();
testQueryBar();
}
public static void testSaveBar() {
Bar bar = new Bar(bar);
Session session = HibernateSessionFactorygetSession();
sessionsave(bar);
sessionbeginTransaction(mit();
sessionclose();
}
public static void testQueryBar() {
Session session = HibernateSessionFactorygetSession();
String hql = from Bar;
Query query = sessioncreateQuery(hql);
List<Bar> barList = querylist();
Collectionssort(barList);
for (Bar bar : barList) {
Systemoutprintln(bargetId() + :\t + bargetTimestamp()getTime());
}
sessionclose();
}
public static void testUpdateBar() {
Session session = HibernateSessionFactorygetSession();
String hql = from Bar;
Query query = sessioncreateQuery(hql);
List<Bar> barList = querylist();
for (Bar bar : barList) {
barsetName(newBar);
}
sessionbeginTransaction(mit();
sessionclose();
}
}
public class TestStack {
public static void main(String args[]){
test();
}
public static void test(){
Stack stack = new Stack();
String s= ;
String s=;
String s= ;
String s= ;
stackpush(s);
stackpush(s);
stackpush(s);
stackpush(s);
for(;!stackisEmpty();){
Systemoutprintln(stackpop());
}
//for语句先判断是否符合条件然后确定是否执行循环
for(int i=;i>;i){
Systemoutprintln(>>> +i);
}
}
}
下面是SessionFactory工具和hibernate配置文件
import orghibernateHibernateException;
import orghibernateSession;
import orghibernatecfgConfiguration;
/**
* Configures and provides access to Hibernate sessions tied to the
* current thread of execution Follows the Thread Local Session
* pattern see {@link }
*/
public class HibernateSessionFactory {
/**
* Location of hibernatecfgxml file
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file
* The default classpath location of the hibernate config file is
* in the default package Use #setConfigFile() to update
* the location of the configuration file for the current session
*/
private static String CONFIG_FILE_LOCATION = /hibernatecfgxml;
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static orghibernateSessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
nfigure(configFile);
sessionFactory = configurationbuildSessionFactory();
} catch (Exception e) {
Systemerr
println(%%%% Error Creating SessionFactory %%%%);
eprintStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance Lazy initialize
* the <code>SessionFactory</code> if needed
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocalget();
if (session == null || !sessionisOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactoryopenSession()
: null;
threadLocalset(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
nfigure(configFile);
sessionFactory = configurationbuildSessionFactory();
} catch (Exception e) {
Systemerr
println(%%%% Error Creating SessionFactory %%%%);
eprintStackTrace();
}
}
/**
* Close the single hibernate session instance
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocalget();
threadLocalset(null);
if (session != null) {
sessionclose();
}
}
/**
* return session factory
*
*/
public static orghibernateSessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernanfigFile = configFile;
sessionFactory = null;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
<?xml version= encoding=UTF?>
<!DOCTYPE hibernateconfiguration PUBLIC
//Hibernate/Hibernate Configuration DTD //EN
configurationdtd>
<! Generated by MyEclipse Hibernate Tools >
<hibernateconfiguration>
<sessionfactory>
<property name=connectionusername>root</property>
<property name=connectionurl>
jdbc:mysql://localhost:/testdb
</property>
<property name=dialect>
orghibernatedialectMySQLDialect
</property>
<property name=nnectionprofile>
commysqljdbcDriver
</property>
<property name=connectionpassword>leizhimin</property>
<property name=connectiondriver_class>
commysqljdbcDriver
</property>
<property name=show_sql>true</property>
<!<property name=format_sql>true</property>>
<property name=hbmddlauto>create</property>
<mapping resource=stu/onemany/pojo/Tclasshbmxml />
<mapping resource=stu/onemany/pojo/Studenthbmxml />
<mapping resource=stu/onemany/pojo/Foohbmxml></mapping>
<mapping resource=stu/onemany/pojo/Barhbmxml />
</sessionfactory>
</hibernateconfiguration>
数据库用的是mysqlsql脚本我导出了一份如下
/*
SQLyog Enterprise MySQL GUI v
MySQL communitynt : Database testdb
*********************************************************************
*/
/*! SET NAMES utf */;
/*! SET SQL_MODE=*/;
/*! SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS FOREIGN_KEY_CHECKS= */;
/*! SET @OLD_SQL_MODE=@@SQL_MODE SQL_MODE=NO_AUTO_VALUE_ON_ZERO */;
create database if not exists testdb;
USE testdb;
/*Table structure for table bar */
DROP TABLE IF EXISTS bar;
CREATE TABLE bar (
id bigint() NOT NULL auto_increment
timestamp datetime NOT NULL
name varchar() NOT NULL
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;
/*Table structure for table foo */
DROP TABLE IF EXISTS foo;
CREATE TABLE foo (
pid bigint() NOT NULL auto_increment
version int() NOT NULL
name varchar() NOT NULL
PRIMARY KEY (pid)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;
/*Table structure for table student */
DROP TABLE IF EXISTS student;
CREATE TABLE student (
sid bigint() NOT NULL auto_increment
fk_cid bigint() NOT NULL
sname varchar() NOT NULL
PRIMARY KEY (sid)
KEY FKFFEBAA (fk_cid)
CONSTRAINT FKFFEBAA FOREIGN KEY (fk_cid) REFERENCES tclass (cid)
) ENGINE=InnoDB AUTO_INCREMENT= DEFAULT CHARSET=gbk;
/*Table structure for table tclass */
DROP TABLE IF EXISTS tclass;
CREATE TABLE tclass (
cid bigint() NOT NULL auto_increment
cname varchar() NOT NULL
PRIMARY KEY (cid)
) ENGINE=InnoDB AUTO_INCREMENT= DEFAULT CHARSET=gbk;
/*! SET SQL_MODE=@OLD_SQL_MODE */;
/*! SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
具体测试运行的结果运行下即可看到