MyBatis框架中Mapper类中方法的返回类型问题解决方案

来源:互联网 发布:平板电脑淘宝开店认证 编辑:程序博客网 时间:2024/06/03 12:56

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的全类名
测试一下:

@Testpublic 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就把全部的映射规则都写上,不写是因为列名和属性名是对应的

原创粉丝点击