实验4《JavaWeb程序设计》_第1页
实验4《JavaWeb程序设计》_第2页
实验4《JavaWeb程序设计》_第3页
实验4《JavaWeb程序设计》_第4页
实验4《JavaWeb程序设计》_第5页
已阅读5页,还剩13页未读, 继续免费阅读

下载本文档

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

文档简介

1、淮海工学院计算机工程学院实验报告书课程名: Java Web程序设计 题 目: 使用Hibernate快速实现持久层处理 班 级: 软件 学 号: 姓 名: 评语:成绩: 指导教师: 批阅时间: 年 月 日一、实验目的掌握Hibernate框架的基本使用方法,能够完成Java对象与数据表的映射定义,实现对象与对象间的一对多关联。二、实验内容基于Hibernate框架完成具有一对多关系的两类对象的数据持久化操作。三、实验方法和步骤1、创建一个动态Web项目,项目名称为:HibernateEx。2、从下载struts2.1-hibernate3-mysqljdbc-lib.r

2、ar,将其中的jar文件解压到WEB-INF/lib文件夹中。3、准备Mysql实验环境。从下载wamp-server-wamp5-2.0h.zip解压后安装其中的wamp。执行以下SQL语句,创建两个表:CREATE TABLE guestbook ( id int(11) NOT NULL auto_increment, userid int(11) NOT NULL, title varchar(500) default NULL, contents varchar(1000) default NULL, PRIMARY KEY (id), KEY userid (

3、userid);CREATE TABLE user ( id int(11) NOT NULL auto_increment, username varchar(50) default NULL, password varchar(50) default NULL, firstname varchar(50) default NULL, lastname varchar(50) default NULL, age int(11) default NULL, PRIMARY KEY (id);4、创建Hibernate 会话工厂类:package test;import org.hibernat

4、e.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 HibernateSe

5、ssionFactory /* * 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 l

6、ocation 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.SessionFactor

7、y 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 HibernateSessionFactor

8、y() /* * 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 (s

9、essionFactory = 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

10、 = 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 = (Sess

11、ion) 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

12、void setConfigFile(String configFile) HibernateSessionFactory.configFile = configFile;sessionFactory = null;/* * return hibernate configuration * */public static Configuration getConfiguration() return configuration;5、创建User类:package com.un;import java.util.ArrayList;import java.util.HashSet;import

13、java.util.List;import java.util.Set;public class User / Fieldsprivate Integer id;private String username;private String password;private Set gbset = new HashSet(); private List gblist=new ArrayList();private static final long serialVersionUID = -2L; / Constructorspublic void setGbset(Set gbset) this

14、.gbset = gbset;public void addGb(Guestbook gb)gb.setUser(this);gbset.add(gb);gblist.add(gb);public Set getGbset() return gbset;public List getGblist() return gblist;public void setGblist(List gblist) this.gblist = gblist;/* default constructor */public User() /* full constructor */public User(String

15、 username, String password) this.username = username;this.password = password;/ Property accessorspublic Integer getId() return this.id;public void setId(Integer id) this.id = id;public String getUsername() return this.username;public void setUsername(String username) this.username = username;public

16、 String getPassword() return this.password;public void setPassword(String password) this.password = password;6、创建Guestbook.javapackage com.un;import java.sql.Timestamp;/* * Guestbook entity. author MyEclipse Persistence Tools */public class Guestbook implements java.io.Serializable / Fieldsprivate s

17、tatic final long serialVersionUID = -1L; private Integer id;private User user;public User getUser() return user;public void setUser(User user) this.user = user;private String title;private String contents;private Timestamp pubdate;/ Constructors/* default constructor */public Guestbook() / Property

18、accessorspublic Integer getId() return this.id;public void setId(Integer id) this.id = id;public String getTitle() return this.title;public void setTitle(String title) this.title = title;public String getContents() return this.contents;public void setContents(String contents) this.contents = content

19、s;public Timestamp getPubdate() return this.pubdate;public void setPubdate(Timestamp pubdate) this.pubdate = pubdate;7、创建映射文件: !- /查询结果的list中会出现null元素 - 8、创建映射文件: 9、创建hibernate.cfg.xml:rootjdbc:mysql:/localhost:3306/testorg.hibernate.dialect.MySQLDialectMySqlcom.mysql.jdbc.Driver10、选中项目新建一个测试类,代码如下:

20、package test;import java.util.Date;import java.util.Iterator;import java.util.List;import java.util.Set;import test.HibernateSessionFactory;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.Transaction;import com.un.Guestbook;import com.un.User;public class TestHibernate p

21、ublic static void main(String args) /saveUserGb();printAllGuestbook();public static void saveUserGb()Session session=HibernateSessionFactory.getSession();Query query=session.createQuery(from User u where u.id=1 /from User u where u.username like z% );List u=query.list();User user;user=u.size()0?(Use

22、r)u.get(0):null;if(user=null)user=new User();user.setUsername(zmofun);user.setPassword(zmofun);session.save(user);printUserGbset(user);printUserGblist(user);Guestbook gb=new Guestbook();Date date=new Date();gb.setTitle(留言标题+date.toString();Transaction tx=session.beginTransaction();/如果gblist的reverse为

23、fase,则保存user时,自动保存gb。user.addGb(gb);session.update(user);/如果gblist的reverse为true,则保存gb时,自动保存user。/gb.setUser(user);/user.getGbset().add(gb);/user.getGblist().add(0,gb);/session.save(gb);mit();printUserGbset(user);printUserGblist(user);session.close();public static void printUserGblist(User user

24、)if(user!=null)List gblist=user.getGblist();if(gblist=null)return;System.out.println(String.format(username:%s,gblist:%s,user.getUsername(),gblist.size();Iterator iter = gblist.iterator();while(iter.hasNext() Guestbook g = (Guestbook)iter.next(); /if(g2!=null) System.out.println(title:+g.getTitle();public static void printUserGbset(User user)if(user!=null)Set gbset=user.getGbset();if(gbset=null)return;System.out.println(String.fo

温馨提示

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

评论

0/150

提交评论