zoukankan      html  css  js  c++  java
  • MyBatis框架中Mapper类中方法的返回类型问题解决方案

    MyBatis框架中Mapper类中方法的返回类型

    1.void 无返回值类型
    例如:

    public void insertEmp(Employee employee);

    在映射文件EmployeeMapper.xml文件中配置

    <insert id="insertEmp" parameterType="com.neuedu.entity.Employee" >
                insert into employee(e_name,gender,email) values(#{name},#{gender},#{email})
            </insert>

    不用写方法的返回值类型resultType或resultMap

    2.Employee 实体类类型

    public Employee selectEmp(Integer id);

    在映射文件EmployeeMapper.xml文件中配置

    <select id="selectEmp"  resultType="com.neuedu.entity.Employee">
                select id,e_name,gender,email from employee where id = #{id}
            </select>

    要标明resultType的类型,写类的全类名

    3.List 列表类型

    public List<Employee> selectAll();

    在映射文件EmployeeMapper.xml文件中配置

    <select id="selectAll" resultType="com.neuedu.entity.Employee">
            select * from employee
          </select>

    返回值类型resultType的值为列表放入的实体类的全类名

    4.Map 类型,返回单条记录为Map

    public Map<String, Object> selectEmployee(Integer id);

    在映射文件EmployeeMapper.xml文件中配置

    <select id="selectEmployee" resultType="java.util.Map">
            select * from employee where id=#{id}
          </select>

    返回值类型resultType的值为Map的全类名
    测试一下:

    @Test
    public void testselectEmployee(){
            Map<String, Object> map = mapper.selectEmployee(4);
            Set<Entry<String,Object>> entrySet = map.entrySet();
            for (Entry<String, Object> entry : entrySet) {
                System.out.println(entry.getKey()+":"+entry.getValue());
            }
            session.commit();
            session.close();
        }

    5..返回为一个ResultMap:自定义结果集映射规则
    尤其是当数据表的列名和类的属性名不对应的时候,处理方法:
    1.起别名
    2.符合下划线转驼峰式命名规范
    3.用这里的resultMap

    <select id="selectEmp"  resultMap="getemployee">
                select id,e_name,gender,email from employee where id = #{id}
            </select>
            <resultMap id="getemployee" type="com.neuedu.entity.Employee">
                <id column="id" property="id"/>
                <result column="e_name" property="name"/>
            </resultMap>

    type:自定义规则的javabean类型 ; id:唯一id方便引用
    指定主键列的封装规则:
    1.id定义主键列会有底层优化
    2.column:指定是哪一列
    3.property:指定对应的javaBean属性
    其它不指定的列只要属性名和列名会自动封装,我们只要写resultMap就把全部的映射规则都写上,不写是因为列名和属性名是对应的

  • 相关阅读:
    设计模式学习--Abstarct Factory
    WPF使用Canvas绘制可变矩形
    离线安装 Android 4.0 SDK
    引用了System.Configuration命名空间,却找不到ConfigurationManager类
    LIBXML2库使用指南2
    Quartz任务调度实践
    FastJson 自定义Serialize、Parser
    maven安装与创建多模块项目
    Zookeeper源码调试环境踩坑记录
    Apache Dubbo时间轮HashedWheelTimer算法的实现原理
  • 原文地址:https://www.cnblogs.com/mazhitao/p/7487953.html
Copyright © 2011-2022 走看看