dao接口
User myGetUserById(Integer id);
sql xml自定义封装规则
<!--自定义某个javabean的封装规则
type:自定义规则的java类型
id:唯一标识方便引用
-->
<resultMap id="myUser" type="com.yunqing.mybatis.bean.User"> <!--id指定主键列的封装规则,return指定普通列的封装规则 column:数据库列名 property:对应的javabean属性 --> <id column="id" property="id"/> <result column="name" property="name"/> <result column="age" property="age"/> </resultMap> <!--使用自定义封装规则--> <select id="myGetUserById" resultMap="myUser"> SELECT * FROM t_user WHERE id = #{id} </select>
test测试类
@Test public void myGetUserById() throws IOException { String r = "mybatis-config.xml"; InputStream is = Resources.getResourceAsStream(r); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sqlSessionFactory.openSession(true); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.myGetUserById(1); System.out.println(user); }
关于级联映射结果集的规则:
javabean的User.java
private Integer id; private String name; private Integer age; private Department dep;//所属部门
Department.java
private Integer id;//部门id
private String departmentName;//部门名
通过用户id查询用户和部门信息
User getUserAndDepById(Integer id);
returnMap映射级联结果集
第一种:
<!-- 自定义结果集,使用级联属性封装第一种方式--> <resultMap id="myMapJiLian" type="com.yunqing.mybatis.bean.User"> <id column="id" property="id"/> <result column="name" property="name"/> <result column="age" property="age"/> <result column="did" property="dep.id"/> <result column="dep_name" property="dep.departmentName"/> </resultMap> <!--使用级联属性--> <select id="getUserAndDepById" resultMap="myMapJiLian"> SELECT u.id id,u.name name,u.age age,u.dep_id dep_id,dep.id did,dep.department dep_name FROM t_user u,t_dep dep WHERE u.dep_id=dep.id AND u.id=#{id} </select>
第二种
<!-- 自定义结果集第二种方式 association可以指定联合javabean对象 property指定那个属性是联合的对象即外键 javaType不能省略,指定这个属性对象的类型 --> <resultMap id="myMapAss" type="com.yunqing.mybatis.bean.User"> <id column="id" property="id"/> <result column="name" property="name"/> <result column="age" property="age"/> <association property="dep" javaType="com.yunqing.mybatis.bean.Department"> <id column="did" property="id"/> <result column="dep_name" property="departmentName"/> </association> </resultMap> <!--使用级联属性--> <select id="getUserAndDepById" resultMap="myMapAss"> SELECT u.id id,u.name name,u.age age,u.dep_id dep_id,dep.id did,dep.department dep_name FROM t_user u,t_dep dep WHERE u.dep_id=dep.id AND u.id=#{id} </select>