MyBatis映射

MybatisUtil

/**
 *实现SqlSessionFactory 单例,生命周期整个应用 
 */
public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory;
    private static  MyBatisUtil myBatisUtil;
    //静态块,实现SqlSessionFactory单例
    //静态块只会被执行一次
    static{
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static SqlSession createSqlSession(){
        return sqlSessionFactory.openSession(true);//true 为自动提交事务
    }
    
    public static void closeSqlSession(SqlSession sqlSession){
        if(null != sqlSession) 
            sqlSession.close();
    }
}

SQL映射的XML文件

  1. MyBatis 真正的强大在于映射语句,专注于SQL,功能强大,SQL映射的配置却是相当简单

  2. SQL映射文件的几个顶级元素(按照定义的顺序)

    • mapper - namespace

    • cache - 配置给定命名空间的缓存

    • cache-ref – 从其他命名空间引用缓存配置

    • resultMap –用来描述数据库结果集和对象的对应关系

    • sql – 可以重用的SQL块,也可以被其他语句引用

    • insert – 映射插入语句

    • update – 映射更新语句

    • delete – 映射删除语句

    • select – 映射查询语句

mapper

  1. namespace:命名空间

    • namespace和子元素的id联合保证唯一,区别不同的mapper

      • 绑定DAO接口

      • namespace的命名必须跟某个接口同名

      • 接口中的方法与映射文件中SQL语句id一一对应

<mapper namespace="com.zking.ssm.dao.UserMapper">
    <select id="getUserList" resultType="User">
        select * from smbms_user
    </select>

select

  1. select是MyBatis中最常用的元素之一

  2. select语句有很多属性可以详细配置每一条语句

    • id

      • 命名空间中唯一的标识符

      • 接口中的方法与映射文件中的SQL语句id一一对应

    • parameterType

      • 传入SQL语句的参数类型

    • resultType

      • SQL语句返回值类型的完整类名或别名

  public List<User> getUserListByUserName(String userName);
    
    <!-- 根据用户名称查询用户列表(模糊查询) -->
    <select id="getUserListByUserName" resultType="User" parameterType="String">
        select * from smbms_user where userName like CONCAT ('%',#{userName},'%')
    </select>
  • 按条件查询用户表,若多条件情况下如何处理? 传入多个参数进行入参? 封装成User对象进行入参?
  1. parameterType

    • 基础数据类型

      • int、String、Date等

      • 只能传入一个,通过#{参数名}即可获取传入的值

      • 在if等条件中使用_parameter读取单个参数

    • 复杂数据类型

      • Java实体类、Map等

      • 通过#{属性名}或者#{map的keyName}即可获取传入值

/**
     * 查询用户列表(参数:Map)
     * @return
     */
    public List<User> getUserListByMap(Map<String, String> userMap);
    
    <!-- 查询用户列表(参数:Map) -->
    <select id="getUserListByMap" resultType="User" parameterType="Map">
        select * from smbms_user 
            where userName like CONCAT ('%',#{uName},'%') and userRole = #{uRole}
    </select>
  1. @Param注解

public List<User> getUserListByNameRole(@Param("userName") String userName,
                                            @Param("userRole") Integer userRole);
                                            
<select id="getUserListByNameRole" resultType="User" >
        select * from smbms_user
            where userName like CONCAT ('%',#{userName},'%') and userRole = #{userRole}
</select>        
  • 按条件查询得到用户表列表,需要显示指定字段,并显示用户角色(中文表述)
  1. resultMap

  • 描述如何将结果集映射到Java对象

<resultMap type="User" id="userMap">
    <result property="id" column="id"/>
    <result property="userCode" column="userCode"/>
    <result property="userName" column="userName"/>
    <result property="userRole" column=“userRole"/>
    <result property="userRoleName" column="roleName"/>
</resultMap>
<select id="getUserList" resultMap="userMap" parameterType="User">
    select u.*,r.roleName from smbms_user u,smbms_role r 
            where u.userName like CONCAT (‘%’,#{userName}, ‘%’)  
            and u.userRole = #{userRole} and u.userRole = r.id 
</select>
​

property:表示查询出来的属性对应的值赋给实体对象的哪个属性

column:从数据库中查询的列名或者别名

resultMap="userMap":一个外部resultMap的id,表示返回结果映射到哪一个resultMap上

  1. resultType & resultMap

    • resultType :直接表示返回类型

      • 基本数据类型

      • 复杂数据类型

    • resultMap :对外部resultMap的引用

      • 应用场景:

        • 数据库字段信息与对象属性不一致

        • 复杂的联合查询,自由控制映射结果

    • 二者不能同时存在,本质上都是Map数据结构

  • 使用resultMap如何实现自由灵活的控制映射结果,从而达到只对关心的属性进行赋值填充?
  1. autoMappingBehavior

    • 所在类:org.apache.ibatis.builder.xml.XMLConfigBuilder

    • resultMap自动映射匹配前提:字段名与属性名一致

    • resultMap的自动映射级别-autoMappingBehavior

      • PARTIAL(默认):自动映射没有定义嵌套结果映射的字段

      • FULL 自动映射任何复杂的结果集

      • NONE 关闭自动映射

<settings>
    <setting  name="autoMappingBehavior" value="NONE"/>
</settings>

select小结

id在命名空间中唯一的标识符,可以被用来引用这条语句
parameterType将会传入这条语句的参数类的完全限定名或别名
resultType从这条语句中返回的期望类型的类的完全限定名或别名。注意集合情形,那应该是集合可以包含的类型,而不能是集合本身。使用resultType或resultMap,但不能同时使用
resultMap命名引用外部的resultMap
flushCache将其设置为true,不论语句什么时候被调用,都会导致缓存被清空。默认值:false
useCache将其设置为true,将会导致本条语句的结果被缓存。默认值:true
timeout这个设置驱动程序等待数据库返回请求结果,并抛出异常时间的最大等待值。默认不设置(驱动自行处理)
fetchSize这是暗示驱动程序每次批量返回的结果行数
statementTypeSTATEMENT,PREPARED或CALLABLE的一种。让MyBatis选择使用Statement,PreparedStatement或CallableStatement。默认值:PREPARED
resultSetTypeFORWARD_ONLY|SCROLL_SENSITIVE|SCROLL_INSENSITIVE中的一种。默认是不设置(驱动自行处理)

insert

<insert  id="save" parameterType="User" >
 insert into  smbms_user (userCode,userName,userPassword) 
        values ( #{userCode},#{userName},#{userPassword})
</insert>

insert、update、delete元素均没有resultType属性

update

<update id ="update" parameterType="User">
update smbms_user set userCode = #{userCode},
             userName = #{userName},
              userPassword = #{userPassword}  where id = #{id}
</update>
  • 实现超市账单管理系统-修改个人密码功能
 public int updatePwd(@Param("id")Integer id, @Param("userPassword")String pwd);
    
    <!-- 修改当前用户密码 -->
    <update id="updatePwd">
        update smbms_user set userPassword=#{userPassword} where id=#{id}
    </update>

delete

<delete id ="deleteUserById" parameterType="int">
    delete from smbms_user where id = #{id}
</delete>

小结

  1. DAO层接口方法常见的返回类型

    • Java对象、Map、List等复杂数据类型

    • int

      • (增删改)更新操作时,影响的数据行数

  2. MyBatis参数入参

    • @Param注解参数

    • 封装成对象入参

resultMap

  • resultMap属性

    • id:resultMap的唯一标识

    • type:Java实体类

  • resultMap子元素

    • id: 一般对应数据库中该行的主键id,设置此项可提高MyBatis性能

    • result: 映射到JavaBean的某个“简单类型”属性

    • association: 映射到JavaBean的某个“复杂类型”属性,比如JavaBean类

    • collection: 映射到JavaBean的某个“复杂类型”属性,比如集合

association

  • 复杂的类型关联,一对一

    • 内部嵌套

      • 映射一个嵌套JavaBean属性

    • 属性

      • property:映射数据库列的实体对象的属性

      • javaType:完整Java类名或者别名

      • resultMap:引用外部resultMap

    • 子元素

      • id

      • result

      • property:映射数据库列的实体对象的属性

      • column:数据库列名或者别名

<!-- 根据roleId获取用户列表 association start-->
	<resultMap type="User" id="userRoleResult">
		<id property="id" column="id"/>
		<result property="userCode" column="userCode" />
		<result property="userName" column="userName" />
		<result property="userRole" column="userRole" />
		<association property="role" javaType="Role" resultMap="roleResult"/>
	</resultMap>
	
	<resultMap type="Role" id="roleResult">
		<id property="id" column="r_id"/>
		<result property="roleCode" column="roleCode"/>
		<result property="roleName" column="roleName"/>
	</resultMap>
	
	<select id="getUserListByRoleId" parameterType="Integer" resultMap="userRoleResult">
		select u.*,r.id as r_id,r.roleCode,r.roleName from smbms_user u,smbms_role r 
				where u.userRole = #{userRole} and u.userRole = r.id
	</select>

collection

  • 复杂类型集合,一对多

  • 内部嵌套

    • 映射一个嵌套结果集到一个列表

  • 属性

    • property:映射数据库列的实体对象的属性

    • ofType:完整Java类名或者别名(集合所包括的类型)

    • resultMap:引用外部resultMap

  • 子元素

    • id

    • result

    • property:映射数据库列的实体对象的属性

    • column:数据库列名或者别名

<!-- 获取指定用户的地址列表(user表-address表:1对多关系) collection start-->
	<resultMap type="User" id="userAddressResult">
		<id property="id" column="id"/>
		<result property="userCode" column="userCode"/>
		<result property="userName" column="userName"/>
		<collection property="addressList" ofType="Address">
			<id property="id" column="a_id"/>
			<result property="postCode" column="postCode"/>
			<result property="tel" column="tel"/>
			<result property="contact" column="contact"/>
			<result property="addressDesc" column="addressDesc"/>
		</collection>
	</resultMap>
	
	<select id="getAddressListByUserId" parameterType="Integer" resultMap="userAddressResult">
		select u.*,a.id as a_id,a.contact,a.addressDesc,a.postCode,a.tel
				from smbms_user u,smbms_address a where u.id = a.userId and u.id=#{id}
	</select>

总结

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值