初学hibernate时,一对多测试代码。

hibernate(一对多的关系)总结

===================================
测试表结构如下:

tb_calendar 日程表

c_id   主键
c_title   标题
c_content  内容
-----------------------------------
tb_calendarTime 时间表

ct_id   主键
ct_cid   关联tb_calendar表c_id字段,建立关系
ct_date   日期
ct_time   时间
====================================

TbCalendar.java <==> 持久化对象

package calendar.model;
import java.io.Serializable;
import org.apache.commons.lang.builder.ToStringBuilder;

public class TbCalendar  implements Serializable {
 private static final long serialVersionUID = 1L;
 private Integer CId;
 private String CContent;
 private String CTitle;
 private java.util.Set<TbCalendartime> tbCalendartimes;

    public TbCalendar() {
     }

 public Integer getCId() {
  return this.CId;
 }
 public void setCId(Integer CId) {
  this.CId = CId;
 }

 public String getCContent() {
  return this.CContent;
 }
 public void setCContent(String CContent) {
  this.CContent = CContent;
 }

 public String getCTitle() {
  return this.CTitle;
 }
 public void setCTitle(String CTitle) {
  this.CTitle = CTitle;
 }

 public java.util.Set<TbCalendartime> getTbCalendartimes() {
  return this.tbCalendartimes;
 }
 public void setTbCalendartimes(java.util.Set<TbCalendartime> tbCalendartimes) {
  this.tbCalendartimes = tbCalendartimes;
 }

 public String toString() {
  return new ToStringBuilder(this)
   .append("CId", getCId())
   .toString();
 }
}

-----------------------------------------------

TbCalendar.hbm.xml <==> 关系映射

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class
    name="calendar.model.TbCalendar"
    table="tb_calendar"
    lazy="false">

    <id
        name="CId"
        type="integer"
        column="C_ID"
        length="4"
    >
        <generator class="identity" />
    </id>
    <property
        name="CContent"
        type="string"
        column="C_Content"
        length="500"
    />
    <property
        name="CTitle"
        type="string"
        column="C_Title"
        length="50"
    />

    <!--cascade 是级联的程度,而inverse="false" 是指维持两个实体的关系。-->
    <set name="tbCalendartimes" cascade="all" inverse="true" lazy="false">
     <key>
      <column name="CT_CID" />
     </key>
     <one-to-many class="calendar.model.TbCalendartime" />
    </set>

</class>
</hibernate-mapping>

====================================

TbCalendarTime.java <==> 持久化对象

package calendar.model;
import java.io.Serializable;
import org.apache.commons.lang.builder.ToStringBuilder;

public class TbCalendartime  implements Serializable {
 private static final long serialVersionUID = 1L;
 private Long ctId;
 private java.sql.Date ctDate;
 private java.sql.Time ctTime;
 private TbCalendar tbCalendar;

    public TbCalendartime() {
     }

 public Long getCtId() {
  return this.ctId;
 }
 public void setCtId(Long ctId) {
  this.ctId = ctId;
 }

 public java.sql.Date getCtDate() {
  return this.ctDate;
 }
 public void setCtDate(java.sql.Date ctDate) {
  this.ctDate = ctDate;
 }

 public java.sql.Time getCtTime() {
  return this.ctTime;
 }
 public void setCtTime(java.sql.Time ctTime) {
  this.ctTime = ctTime;
 }

 public TbCalendar getTbCalendar() {
  return this.tbCalendar;
 }
 public void setTbCalendar(TbCalendar tbCalendar) {
  this.tbCalendar = tbCalendar;
 }

 public String toString() {
  return new ToStringBuilder(this)
   .append("ctId", getCtId())
   .toString();
 }
}

------------------------------

TbCalendarTime.hbm.xml  <==> 关系映射

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class
    name="calendar.model.TbCalendartime"
    table="tb_calendartime"
    lazy="false"
>
    <id
        name="ctId"
        type="long"
        column="CT_ID"
        length="8"
    >
        <generator class="identity" />
    </id>
    <property
        name="ctDate"
        type="date"
        column="CT_Date"
        length="10"
    />
    <property
        name="ctTime"
        type="time"
        column="CT_Time"
        length="8"
    />

    <!-- insert="true",update="true" 联级互动-->
    <many-to-one
        name="tbCalendar"
        class="calendar.model.TbCalendar"
        lazy="false"
    insert="true" update="true">
        <column name="CT_CID" length="4"/>
    </many-to-one>

</class>
</hibernate-mapping>

######################################################################
######################################################################

增加及修改:
 说明:可将增加和修改写在一个类方法中,因为hibernate的运行机制首先将查询提交过来的数据对象是否存在,如果为NULL值,则写入新的数据。如果存在该值,则进行修改。

 //类方法(addEditCalendare):
 public boolean addEditCalendare(TbCalendar calendar) {
  boolean result = false;
  session.beginTransaction();
  try {
   session.saveOrUpdate(calendar);
   session.flush();
   session.getTransaction().commit();
   result = true;
  }catch (Exception errors) {
   session.getTransaction().rollback();
   errors.printStackTrace();
   
  }finally {
   HibernateUtil.closeSession();
  }
  return result;
 }

 //测试方法:
 //添加日程测试模块
 public void testAddCalendar(){
  TbCalendar calendar = new TbCalendar();
  
  calendar.setCTitle("Hello World");
  calendar.setCContent("Today is good day");
  
  Set<TbCalendartime> calendartimeSet = new HashSet<TbCalendartime>();
  TbCalendartime calendartime = new TbCalendartime();
  long now = System.currentTimeMillis();
  calendartime.setCtDate(new Date(now));
  calendartime.setCtTime(new Time(now));
  calendartime.setTbCalendar(calendar);
  calendartimeSet.add(calendartime);
  
  calendar.setTbCalendartimes(calendartimeSet);
  
  log.info("添加是否成功 : " + dao.addEditCalendare(calendar));
 }

 //修改日程测试模块
 public void testEditCalendar(){
  TbCalendar calendar = dao.findCalendareById(new Integer(17));
  Set<TbCalendartime> tcs = calendar.getTbCalendartimes();
  for (TbCalendartime calendartime : tcs) {
   long now = System.currentTimeMillis();
   calendartime.setCtDate(new Date(now));
   calendartime.setCtTime(new Time(now));
  }
  calendar.setCTitle("test update 13");
  log.info("修改是否成功: " + dao.addEditCalendare(calendar));
 }
***************************************************************************

删除:

 方法1:

 //类方法(deleteCalendare)
 public boolean deleteCalendare(TbCalendar calendar){
  boolean result = false;
  session.beginTransaction();
  try{
   session.delete(calendar);
          session.getTransaction().commit();
          result = true;
  }catch(Exception errors){
   session.getTransaction().rollback();
   errors.printStackTrace();
  }finally{
   HibernateUtil.closeSession();
  }
  return result;
 }
 
 //测试方法
 //删除日程测试模块
 public void testdeleteCalendar(){
  TbCalendar calendar = dao.findCalendareById(new Integer(17));
  log.info("删除是否成功: " + dao.deleteCalendare(calendar));
 }

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 方法2:

 //类方法(deleteCalendare)
 public boolean deleteCalendare(int cid){
  boolean result = false;
  session.beginTransaction();
  try{
   TbCalendar calendar = (TbCalendar) session.load(TbCalendar.class, cid);
   session.delete(calendar);
          session.getTransaction().commit();
          result = true;
  }catch(Exception errors){
   session.getTransaction().rollback();
   errors.printStackTrace();
  }finally{
   HibernateUtil.closeSession();
  }
  return result;
 }
 
 //测试方法
 //删除日程测试模块
 public void testdeleteCalendar(SysuserForm sysuerForm.){
  int userid = sysuerForm.getUserid();
  log.info("删除是否成功: " + dao.deleteCalendare(userid));
 }

***************************************************************************

查询:
 //返回单一条记录:
 public TbCalendar findCalendareById(Integer cid){
  TbCalendar result = null;
  try{
   result = (TbCalendar)session.load(TbCalendar.class, cid);
  }catch(Exception errors){
   errors.printStackTrace();
  }finally{
   HibernateUtil.closeSession();
  }
  return result;
 }

 //分页类:
 
 public class AbsQueryMap {

   // 分页为20
   int pagesize = 20;
   // 当前页数
   int pageno = 1;

   //return 分页行数大小(默认为20)
   public int getPagesize() {
    return pagesize;
   }

   //param i 设置分页行数大小
   public void setPagesize(int i) {
    pagesize = i;
   }
  
   //return 返回当前页号,初始值为1
   public int getPageno() {
    return pageno;
   }

   //param i 设置当前页号
   public void setPageno(int i) {
    pageno = i;
   }

   //设置查询分页
   public void setQueryPage(Query query) {
     // 设置分页起始记录号
     query.setFirstResult((this.pageno - 1) * this.pagesize);
     // 设置页内数据量
     query.setMaxResults(this.pagesize);
   }
 }

 public class SysUserQueryMap extends AbsQueryMap {
   public SysUserQueryMap() throws HibernateException {
     this.initSession();
   }

   public Iterator findAllSysUser() throws HibernateException {
     // 查询语句
     String querystr = "FROM SysUser";
     // 创建查询
     Query query = this.session.createQuery(querystr);
     // 设置分页
     this.setQueryPage(query);
     // 返回查询出的结果集
     return query.iterate();
   }

   public Iterator getSomeCourse(String name)throws HibernateException {
         String queryString = "select c from Course as c where c.name like :name" ;
          session.beginTransaction();
          Query query = session.createQuery(queryString);
           query.setString("name", "%"+name+"%");
     // 设置分页
     this.setQueryPage(query);
          return query.iterate();
      }
 }

 ------------------------------------------

 //JSP中使用方法:

 <%
 try{
     Iterator it=SysUserQueryMap.getSomeCourse((String)request.getParameter("name"));
     while(it.hasNext()) {
        Course temp=(Course)it.next();
        out.println("<tr><td>"+temp.getId()+"</td>");
        out.println("<td>"+temp.getName()+"</td></tr>");
     }
   }
   catch(Exception e){
      out.println(e.getMessage());
    }
 %>

 -------------------------------------------

 在Action中调用:
   if (action == null || action.equals("list")) {
     //如果处理请求类型为list
     SysUserQueryMap sqm = new SysUserQueryMap();
     Iterator sysuserlist = sqm.findAllSysUser();
     request.setAttribute("sysuserlist", sysuserlist);
     action = "list";
     } 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值