MyBatis对整合多个表的类的操作

来源:互联网 发布:中信淘宝信用卡权益 编辑:程序博客网 时间:2024/06/05 10:08

前言

前几天在实现oj的DAO层时,由于将problem表中的一些字段拿出来做了字典表,导致了数据库表过多,如果还是像以前一样:一个数据库表对应一个实体类的话,这样不仅会增加好多重复性的工作,还会使得逻辑层的编写变得复杂。

解决方法

于是,我们将关联密切的表整合为一个实体类,这样来简化DAO层的实现。下面就来看看DAO层是如何实现的吧。

数据库的关联表

这里我对题目字典表做了简化。

CREATE TABLE `dict_problem` (  `id` int(10) NOT NULL auto_increment COMMENT 'ID',  `problemAlgorithmId` int(11) DEFAULT NULL COMMENT '算法字典表ID',  `problemStructureId` int(11) DEFAULT NULL COMMENT '数据结构字典表ID',  PRIMARY KEY  (`id`)) ENGINE=InnoDB AUTO_INCREMENT = 1001 DEFAULT CHARSET=utf8 COMMENT='题目字典表';
CREATE TABLE `dict_problem_algorithm` (  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',  `type` varchar(50) DEFAULT NULL COMMENT '算法的类型',  PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='算法字典表';
CREATE TABLE `dict_problem_structure` (  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',  `type` varchar(50) DEFAULT NULL COMMENT '数据结构的类型',  PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='数据结构字典表';

对应的实体类

public class Problem extends BasicVo{    private int id;                         //ID    private String problemAlgorithm;      //算法字典表    private String problemStructure;      //数据结构字典表    //下面省略了构造函数和get,set方法...}

插入操作

插入需要传入一个Problem的对象,然后dict_problem表进行插入操作,(默认算法字典表,数据结构字典表的数据已存在)
//通过insert...set来实现<insert id="save" parameterType="Problem" >        insert into dict_problem SET        problemAlgorithmId = (SELECT id FROM dict_problem_algorithm WHERE dict_problem_algorithm.type = #{problemAlgorithm} ),        problemStructureId = (SELECT id FROM dict_problem_structure WHERE dict_problem_structure.type = #{problemStructure} )</insert>

查询操作

根据条件将查找的信息放入Problem对象。
<select id="listBatch" resultType="Problem">        select             p.id,            a.type as problemAlgorithm,            s.type as problemStructure         from dict_problem as p        inner join dict_problem_algorithm as a on p.problemAlgorithmId=a.id        inner join dict_problem_structure as s on p.problemStructureId=s.id        <where>            根据Problem的其他字段进行筛选。        </where>        limit #{param2},#{param3}    </select>