Hibernate一对多双向映射及乐观锁使用.doc_第1页
Hibernate一对多双向映射及乐观锁使用.doc_第2页
Hibernate一对多双向映射及乐观锁使用.doc_第3页
Hibernate一对多双向映射及乐观锁使用.doc_第4页
Hibernate一对多双向映射及乐观锁使用.doc_第5页
已阅读5页,还剩7页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Hibernate一对多双向映射及乐观锁使用 例子两部分: 1、一对多双向映射:模型是“班级学生”模型。两个实体分别是Tclass和Student。 2、乐观锁的是使用,版本分别使用递增整数和时间戳。两个实体分别是Foo和Bar。 Tclass实体及其映射: public class Tclass implements java.io.Serializable / Fields private Long cid; private String cname; private Set students = new HashSet(0); / Constructors / Property accessors . public String toString() return Tclass + cid= + cid + , cname= + cname + + ; Student实体及其映射 public class Student implements java.io.Serializable / Fields private Long sid; private Tclass tclass; private String sname; / Constructors / Property accessors . public String toString() return Student + sid= + sid + , sname= + sname + + ; 测试班级学生模型: public class Test /* * param args */ public static void main(String args) testSave(); / testDeleteTclass(); public static void testSave() Tclass c = new Tclass(); c.setCname(某班级); Student s1 = new Student(); Student s2 = new Student(); s1.setSname(张三); s1.setTclass(c); s2.setSname(李四); s2.setTclass(c); c.getStudents().add(s1); c.getStudents().add(s2); Session session = HibernateSessionFactory.getSession(); Transaction tx = session.beginTransaction(); session.save(c); mit(); session.close(); public static void testUpdateClass() System.out.println(-正在调用testUpdateClass()-); Session session = HibernateSessionFactory.getSession(); Tclass c = (Tclass) session.load(Tclass.class, Long.valueOf(1L); System.out.println(c); c.setCname(班级更名); session.beginTransaction().commit(); public static void testUpdateStudent() System.out.println(-正在调用testUpdateStudent()-); Session session = HibernateSessionFactory.getSession(); Tclass c = (Tclass) session.load(Tclass.class, Long.valueOf(3L); Student s = (Student) session.load(Student.class, Long.valueOf(2L); s.setSname(学生改名换姓-王八); s.setTclass(c); System.out.println(c); System.out.println(s); session.beginTransaction().commit(); System.out.println(s); System.out.println(s.getTclass(); public static void testDeleteStudent() System.out.println(-正在调用testDelete()-); Session session = HibernateSessionFactory.getSession(); Student s = (Student) session.load(Student.class, Long.valueOf(5L); System.out.println(s); System.out.println(s.getTclass(); session.delete(s); session.beginTransaction().commit(); public static void testDeleteTclass() System.out.println(-正在调用testDelete()-); Session session = HibernateSessionFactory.getSession(); Tclass c = (Tclass) session.load(Tclass.class, Long.valueOf(3L); System.out.println(c); session.delete(c); session.beginTransaction().commit(); public static void testQueryClass() System.out.println(-正在调用testQueryClass()-); Session session = HibernateSessionFactory.getSession(); Tclass c = (Tclass) session.load(Tclass.class, new Long(1); System.out.println(c); System.out.println(c.getStudents(); public static void testQueryStudent() System.out.println(-正在调用testQueryStudent()-); Session session = HibernateSessionFactory.getSession(); Student s = (Student) session.load(Student.class, new Long(1); System.out.println(s); System.out.println(s.getTclass(); 下面是乐观锁的使用: 1、基于整数的版本控制 Foo实体和映射文件 public class Foo implements java.io.Serializable / Fields private Long pid; private Integer version; private String name; / Constructors / Property accessors . public String toString() return Foo + pid= + pid + , version= + version + , name= + name + + ; 测试: public class TestFoo /* * param args */ public static void main(String args) testSave(); public static void testSave() Foo foo1 = new Foo(foo1); Session session = HibernateSessionFactory.getSession(); session.save(foo1); session.beginTransaction().commit(); session.close(); 2、基于时间戳的版本控制 public class Bar implements java.io.Serializable, 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 = this.id - bar.getId(); return Value(); public class TestBar public static void main(String args) testUpdateBar(); testQueryBar(); public static void testSaveBar() Bar bar = new Bar(bar); Session session = HibernateSessionFactory.getSession(); session.save(bar); session.beginTransaction().commit(); session.close(); public static void testQueryBar() Session session = HibernateSessionFactory.getSession(); String hql = from Bar; Query query = session.createQuery(hql); List barList = query.list(); Collections.sort(barList); for (Bar bar : barList) System.out.println(bar.getId() + :t + bar.getTimestamp().getTime(); session.close(); public static void testUpdateBar() Session session = HibernateSessionFactory.getSession(); String hql = from Bar; Query query = session.createQuery(hql); List barList = query.list(); for (Bar bar : barList) bar.setName(newBar); session.beginTransaction().commit(); session.close(); public class TestStack public static void main(String args) test(); public static void test() Stack stack = new Stack(); String s1= 1; String s2=2; String s3= 3; String s4= 4; stack.push(s1); stack.push(s2); stack.push(s3); stack.push(s4); for(;!stack.isEmpty();) System.out.println(stack.pop(); /for语句先判断是否符合条件,然后确定是否执行循环 for(int i=0;i10;i-) System.out.println( +i); 下面是SessionFactory工具和hibernate配置文件: import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; /* * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see link /42.html . */ public class HibernateSessionFactory /* * Location of hibernate.cfg.xml 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 = /hibernate.cfg.xml; private static final ThreadLocal threadLocal = new ThreadLocal(); private static Configuration configuration = new Configuration(); private static org.hibernate.SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION; static try configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); catch (Exception e) System.err .println(% Error Creating SessionFactory %); e.printStackTrace(); private HibernateSessionFactory() /* * Returns the ThreadLocal Session instance. Lazy initialize * the SessionFactory if needed. * * return Session * throws HibernateException */ public static Session getSession() throws HibernateException Session session = (Session) threadLocal.get(); if (session = null | !session.isOpen() if (sessionFactory = null) rebuildSessionFactory(); session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); return session; /* * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() try configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); catch (Exception e) System.err .println(% Error Creating SessionFactory %); e.printStackTrace(); /* * Close the single hibernate session instance. * * throws HibernateException */ public static void closeSession() throws HibernateException Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) session.close(); /* * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() return sessionFactory; /* * return session factory * * session factory will be rebuilded in the next call */ public static void setConfigFile(String configFile) HibernateSessionFactory.configFile = configFile; sessionFactory = null; /* * return hibernate configuration * */ public static Configuration getConfiguration() return configuration; root jdbc:mysql:/localhost:3306/testdb org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver leizhimin com.mysql.jdbc.Driver true !-true- create 数据库用的是mysql5,sql脚本我导出了一份如下: /* SQLyog Enterprise - MySQL GUI v6.5 MySQL - 5.0.45-community-nt : Database - testdb * */ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=*/; /*!40014 SET OLD_FOREIGN_KEY_CHECKS=FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 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(20) NOT NULL auto_increment, timestamp datetime NOT NULL, name varchar(24) NOT NULL, PRIMARY KEY (id) ) ENGINE=Inno

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论