zoukankan      html  css  js  c++  java
  • jpa 多对多关系的实现注解形式

    1, 表结构

      1)设备表 VTM_DEVICE_INFO

    create table VTM_DEVICE_INFO
    (
      ID                 INTEGER not null,
      SN                 VARCHAR2(32) not null,
      STATUS             INTEGER,
      MEMO               VARCHAR2(256),
      DEVICE_NO          INTEGER,
      START_TIME         TIMESTAMP(6),
      END_TIME           TIMESTAMP(6),
      FACTORY            INTEGER,
      DEVICE_IN_DATE     TIMESTAMP(6),
      ISAFEDOOR_POSITION INTEGER,
      AUDIT_FLAG         VARCHAR2(1)
    );
    alter table VTM_DEVICE_INFO
      add constraint PK_VTM_DEVICE_INFO primary key (ID);
    

      2)模块表 VTM_MODULE_DEFINE

    create table VTM_MODULE_DEFINE
    (
      ID          INTEGER not null,
      MODULE_NAME VARCHAR2(50) not null
    );
    alter table VTM_MODULE_DEFINE
      add constraint PK_VTM_MODULE_DEFINE primary key (ID);

      3)设备模块关系表 VTM_DEVICE_MODULE

    create table VTM_DEVICE_MODULE
    (
      DEVICE_ID INTEGER not null,
      MODULE_ID INTEGER not null
    )
    ;
    alter table VTM_DEVICE_MODULE
      add constraint FK_VTM_DEVI_REF_DEVIC_VTM_DEVI foreign key (DEVICE_ID)
      references VTM_DEVICE_INFO (ID);
    alter table VTM_DEVICE_MODULE
      add constraint FK_VTM_DEVI_REF_DEVIC_VTM_MODU foreign key (MODULE_ID)
      references VTM_MODULE_DEFINE (ID);

      4)初始化模块表数据

    insert into VTM_MODULE_DEFINE (ID, MODULE_NAME) values (1, '读卡器');
    insert into VTM_MODULE_DEFINE (ID, MODULE_NAME) values (2, '密码键盘');
    insert into VTM_MODULE_DEFINE (ID, MODULE_NAME) values (3, '取款模块');
    insert into VTM_MODULE_DEFINE (ID, MODULE_NAME) values (4, '存款模块');

      5)数据库中要到的序列

    create sequence DEVICE_INFO_SEQ
    minvalue 1
    maxvalue 9999999999
    start with 101
    increment by 1
    cache 20;
    
    create sequence DEVICE_MODULE_SEQ
    minvalue 1
    maxvalue 9999999999
    start with 1
    increment by 1
    cache 20;

      设备表 与 模块表 之间是多对多的关系,关系表为 设备模块表

    2,实体类采用注解的形式,体现他们之间的关系

    package opstools.vtm.device.entity;
    
    import java.io.Serializable;
    import java.util.Date;
    import java.util.Set;
    
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.JoinTable;
    import javax.persistence.ManyToMany;
    import javax.persistence.ManyToOne;
    import javax.persistence.SequenceGenerator;
    import javax.persistence.Table;
    import javax.persistence.Temporal;
    import javax.persistence.TemporalType;/**
     * 设备实体类
     * @author yangw
     */
    @Entity
    @Table(name = "VTM_DEVICE_INFO")
    @SequenceGenerator(name = "deviceInfoSeq", sequenceName = "DEVICE_INFO_SEQ")
    public class DeviceInfo implements Serializable {
    
        private static final long serialVersionUID = -6964820074623402896L;
    
        @Id
        @Column(name="ID")
        @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "deviceInfoSeq")
        private Integer deviceId;          //设备Id
        
        @Column
        private String sn;                 //序号
        @Column
        private Integer status;          //设备使用状态
        
        @Column
        private Integer branchId;
        
        @Column
        private String memo;             //备注信息
        @Column
        private Integer deviceNo;        //设备型号
    
        @Temporal(TemporalType.TIMESTAMP)
        @Column
        private Date startTime;         //开始使用时间
        @Temporal(TemporalType.TIMESTAMP)
        @Column
        private Date endTime;            //设备终止时间
        @Column
        private Integer factory;        //设备厂商
        @Temporal(TemporalType.TIMESTAMP)
        @Column
        private Date deviceInDate;        //设备增加时间
        @Column
        private Integer isafedoorPosition;    //开门方向
        @Column
        private Integer auditFlag;        //审核标志
    
        @ManyToMany(cascade=CascadeType.PERSIST)     
        @JoinTable(name = "VTM_DEVICE_MODULE", joinColumns = {@JoinColumn(name = "deviceId")},inverseJoinColumns=@JoinColumn(name="MODULE_ID"))
        private Set<ModuleDefine> moduleDefine;  
        
          //get set 省略
    }
    package opstools.vtm.device.entity;
    
    import java.io.Serializable;
    import java.util.Set;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.JoinTable;
    import javax.persistence.ManyToMany;
    import javax.persistence.SequenceGenerator;
    import javax.persistence.Table;
    
    /**
     * 设备模块表
     * @author yangw
     */
    @Entity
    @Table(name = "VTM_MODULE_DEFINE")
    @SequenceGenerator(name = "moduleDefineSeq", sequenceName = "MODULE_DEFINE_SEQ")
    public class ModuleDefine implements Serializable {
    
        private static final long serialVersionUID = 1L;
    
        @Id
        @Column(name="ID")
        @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "moduleDefineSeq")
        private Integer moduleId;          //模块Id
        
        @Column
        private String moduleName;         //模块名称
    
        @ManyToMany(mappedBy = "moduleDefine")  
        private Set<DeviceInfo> deviceInfo;  
        
        //省略 get set 这个类可能不需要再写@ManyToMany来维护关系,因为这个表的数据是初始化好的,不需要修改, 具体没有测试.
        
    }

    3, dao层的实现,就是将 设备添加到数据库

    @Override
        public void createDeviceInfo(DeviceInfo deviceInfo) {
            super.create(deviceInfo);    
        }

    4,service层的实现,将模块信息设置到设备类的属性中.

    @Override
        public void createDeviceInfo(DeviceInfo deviceInfo, Integer[] moduleIds) {
            if(moduleIds!=null){
                
                Set<ModuleDefine> defineSet=deviceInfo.getModuleDefine();
                if(defineSet==null){
                    defineSet=new HashSet<ModuleDefine>();
                }
                for(int i=0;i<moduleIds.length;i++){
                    ModuleDefine define=new ModuleDefine();
                    define.setModuleId(moduleIds[i]);
                    defineSet.add(define);
                }
                deviceInfo.setModuleDefine(defineSet);
                
            }
            
            deviceInfoDao.createDeviceInfo(deviceInfo);    
            
        }

    5,action层的简单实现

        @Override
        public void submitPage(String pageName) throws Exception {
            
            deviceInfo.setStartTime(DateSupportUtils.str2second(startTime));
            deviceInfo.setEndTime(DateSupportUtils.str2second(endTime));
            
            if(pageName.equals(PAGE_CREATE)){
                deviceInfo.setDeviceInDate(new Date());
                deviceInfoService.createDeviceInfo(deviceInfo,moduleIds);
            }
            else if(pageName.equals(PAGE_UPDATE)){
                deviceInfoService.updateDeviceInfo(deviceInfo);
            }
        }

    6,界面jsp页面,简单给大家看看.

    <%@ page language="java" pageEncoding="UTF-8"%>
    <%@ taglib prefix="s" uri="/struts-tags" %> 
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
        <head>
            <title>${pageTitle}</title>
            <s:include value="../../../include/page.jsp"/>
            <style type="shett"></style>
            <script type="text/javascript" >
              

    //这里的代码是级联获取下拉框数据,省略掉,可以参考上一篇处理json的代码
    </script> </head> <body onload="Page.init('${pageError}','${pageMessage}',${isSubmit})"> <div id="title">${pageTitle}</div> <s:form id="MYFORM" action="%{pageAction}" method="post" theme="simple"> <input type="hidden" value="0" name="deviceInfo.status"/> <input type="hidden" value="0" name="deviceInfo.auditFlag"/> <div id="content"> <table> //下面一种标签只列出来了一个 <tr> <th width="13%">开始使用时间:</th> <td width="35%"><div> <input name="startTime" value="<s:date name="deviceInfo.startTime" format="yyyy-MM-dd HH:mm:ss"/>" class="Wdate" onfocus="WdatePicker({isShowClear:false,dateFmt:'yyyy-MM-dd HH:mm:ss',readOnly:true})"/> </div></td> </tr> <tr> <th width="17%">设备厂商:</th> <td width="35%"><s:select name="deviceInfo.factory" id="deviceFactory" list="deviceFactoryList" listKey="realValue" listValue="displayValue" headerKey="" headerValue="请选择"/> </td> </tr> <tr> <th width="17%">模块:</th> <td width="35%" > <div> <s:checkboxlist name="moduleIds" cssClass="checkbox" list="moduleList" listKey="realValue" listValue="displayValue" > </s:checkboxlist> </div> </td> </tr> <tr> <th width="13%">备注信息:</th> <td width="35%" colspan="3" ><div> <s:textarea name="deviceInfo.memo" onblur="Check.checkLength(this,256)"/> </div></td> </tr> </table> </div> <div id="operator"> <div class="left"></div> <div class="middle" onclick="Page.submit()">提交</div> <div class="right"></div> <div class="left"></div> <div class="middle" onclick="Page.close()">关闭</div> <div class="right"></div> </div> </s:form> </body> </html>
    ----------- 赠人玫瑰,手有余香     如果本文对您有所帮助,动动手指扫一扫哟   么么哒 -----------


    未经作者 https://www.cnblogs.com/xin1006/ 梦相随1006 同意,不得擅自转载本文,否则后果自负
  • 相关阅读:
    Combine 框架,从0到1 —— 4.在 Combine 中使用计时器
    Combine 框架,从0到1 —— 4.在 Combine 中使用通知
    Combine 框架,从0到1 —— 3.使用 Subscriber 控制发布速度
    Combine 框架,从0到1 —— 2.通过 ConnectablePublisher 控制何时发布
    使用 Swift Package Manager 集成依赖库
    iOS 高效灵活地配置可复用视图组件的主题
    构建个人博客网站(基于Python Flask)
    Swift dynamic关键字
    Swift @objcMembers
    仅用递归函数操作逆序一个栈(Swift 4)
  • 原文地址:https://www.cnblogs.com/xin1006/p/3644700.html
Copyright © 2011-2022 走看看