Mybatis快速上手笔记!!!

Mybatis

Mybatis大致流程

  • 创建user表,添加数据
  • 创建模块(xml配置文件),导入坐标
  • 编写MyBatis核心配置文件–>替换连接信息,解决硬编码问题
  • 编写SQL映射文件–>统一管理sql语句,解决硬编码问题
  • 编码
    • 定义POJO类(简单的普通Java类)
    • 加载核心配置文件,获取SqlSessionFactory对象
    • 获取SqlSession对象,执行Sql语句
    • 释放资源

Mapper代理开发(解决原生方式中的硬编码,简化后期执行SQL)

Mapper类里面有许多方法,这些方法一一与配置里的id相对应

  • 定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下(在resource里面建立一个与mapper类相同目录的文件夹)
  • 设置SQL映射文件的namespace属性为Mapper接口全限定名
  • 在 Mapper 接口中定义方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回值类型一致
  • 编码
    • 通过 SqlSession 的 getMapper方法获取 Mapper接囗的代理对象
    • 调用对应方法完成sql的执行
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceStream(resource);
SqlSessionFactory sqlsessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById(1);

Mybatis核心配置文件(每个配置文件需要遵守前后顺序!!

  • environments:配置数据库连接环境信息,可以配置多个environment,通过default属性切换不同的environment
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <!-- 数据库连接信息 -->
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql:///mybatis?useSSL=false" />
                <property name="username" value="root" />
                <property name="password" value="1234" />
            </dataSource>
        </environment>
        <environment id="test">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <!-- 数据库连接信息 -->
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql:///mybatis?useSSL=false" />
                <property name="username" value="root" />
                <property name="password" value="1234" />
            </dataSource>
        </environment>
    </environments>
</configuration>

typeAliases:给pojo下面的实体类取了个别名,不需要区分大小写,并且不需要加上报的名称,写resultType的时候直接写类名就可以了。

<typeAliases>
	<package name="com.itheima.pojo"/>
</typeAliases>

  • 查询所有:

    • 数据库的字段名称和实体类的属性名称不一样,则不能自动封装数据

    • 起别名:对不一样的列名起别名,让别名和实体类的属性名一样。(每次查询都需要定义一次别名)

      select id,brand_name as brandName from tb_brand

    • resultMap映射:完成不一致属性名和列名的映射

    //id唯一标识
    //type映射的类型,支持别名
    //column表的列名
    //property实体类的属性名
    //定义<resultMap>标签,在<select>标签中,使用resultMap属性替换resultType属性
    <resultMap id="brandResultMap" type="brand">
        <reult column="brand_name" property="brandName" />
    </reultMap>
      
    <select id="selectAll" resultMap="brandResultMap">
        select
        *
        from tb_brand
    </select>
    
  • 查看详情

    参数占位符:
    1.#{}会将其替换成?,为了防止sql注入。

    ​ 2.${}拼sql。会存在sql注入问题

    3.使用实际:参数传递要用#{},表名或列名不固定的情况下用${},会存在sql注入问题

​ 参数类型:parameterType:可以省略。

<select id="selectById" parameterType="int" resultMap="brandResultMap">
    select
    *
    from tb_brand where id = #{id}; //#{}会将其替换成?,为了防止sql注入。 ${}拼sql。会存在sql注入问题
</select>

​ 特殊字符处理:

​ 1.转义字符

​ 2.CDATA区:<![CDATA[内容]]>

<select id="selectById" parameterType="int" resultMap="brandResultMap">
    select
    *
    from tb_brand where id <![CDATA[<]]> #{id}; //where id < #{id} 
</select>
  • 条件查询
    • 散装参数:如果方法有多个参数,采用@Param(“SQL参数占位符名称”)
    • 对象参数:对象属性名称要和参数占位符名称一致
    • map参数:保证sql中的参数名和map集合的键的名称对应上
List<Brand> selectByCondition(@Param("status") int status, @Param("companyName") String companyName, @Param("brandName") String brandName);
List<Brand> selectByCondition(Brand brand);
List<Brand> selectByCondition(Map<String, Object> map);
<select id="selectByCondition" resultMap="brandResultMap">
    SELECT * FROM tb_brand
    WHERE status = #{status}
    AND company_name LIKE #{companyName}
    AND brand_name LIKE #{brandName}
</select>
  • 动态条件查询

*if:条件判断

​ *test:逻辑表达式

*问题

​ *恒等式:1=1过渡

<select id="selectByCondition" resultMap="brandResultMap">
    SELECT * FROM tb_brand
    WHERE 1=1 //为了满足语法要求,要不然会出现第一个要求不符合的情况如 where AND company_name LIKE #{companyName}
    <if test="status != null">
    	status = #{status}
	</if>
    <if test="companyName != null and companyName !='' ">	//表达式里只能用and 不能用&&
    	AND company_name LIKE #{companyName}   
    </if>
        <if test="brand_name != null and brand_name !='' ">
    	AND brand_name LIKE #{brandName}
    </if>
</select>

​ * 替换where关键字

<select id="selectByCondition" resultMap="brandResultMap">
    SELECT * FROM tb_brand
    <WHERE> 
        <if test="status != null">
            status = #{status}
        </if>
        <if test="companyName != null and companyName !='' ">	//表达式里只能用and 不能用&&
            AND company_name LIKE #{companyName}   
        </if>
            <if test="brand_name != null and brand_name !='' ">
            AND brand_name LIKE #{brandName}
        </if>
     </where>
</select>

从多个条件中选择一个 choose(when.otherwise):选择,类似Java中的switch语句

<select id="selectByConditionSingle" resultMap="brandResultMap">
	select *
	from tb brand
	<where>
        <choose><!--类似于switch-->
            <when test="status != null"><!--类似于case-->
                status =#{status}
            </when>
            <when test="companyName != null and companyName !="">
                company_name like #{companyName}
            </when>
            <when test="brandName != null and brandName !=" ">
                brand name like #{brandName}
            </when>
        </choose>
   	</where>
</select>

  • Mybatis事务

    • openSession():默认开启事务,进行增删改查操作后需要使用sqlSession.commit();手动提交事务

    • openSession(true):可以设置为自动提交事务(关闭事务)

<insert id="add">
	insert into tb brand (brand name, company _name, ordered, description, status)
    values (#{brandName},#{companyName},#{ordered},#{description},#{status})
</insert>
  • 添加主键返回(数据添加成功之后主键id会出现获取不到的问题)

使用userGeneratedKeys=“true” keyProperty="id"指向id的名称

<insert id="add" userGeneratedKeys="true" keyProperty="id">
	insert into tb brand (brand name, company _name, ordered, description, status)
    values (#{brandName},#{companyName},#{ordered},#{description},#{status})
</insert>

<update id="update">
	update tb_brand
    set brand_name = #{brandName},
		company_name = #{companyName},
		ordered = #fordered}
		description = #description},
		status = #{status} 
	where id = #{id};
</update>
  • 修改动态字段
<update id="update">
	update tb_brand
    <set> 
    	<if test="brand_name != null and brand_name !='' ">
			brand_name = #{brandName},            
        </if>
    	<if test="company_name != null and company_name !='' ">
			company_name = #{companyName},            
        </if>
    	<if test="ordered != null">
			ordered = #{ordered}          
        </if>
    	<if test="description != null and description !='' ">
			description = #{description},            
        </if>
    	<if test="status != null">
			status = #{status}      
        </if>
	</set>
	where id = #{id};
</update>

  • 删除一个
<delete id="deleteById">
    delete from tb_brand where id = #{};
</delete>
  • 删除多个(根据数组删除void deleteByIds(@Param(“ids”) int[] ids))

    • mybatis会将数组参数,封装成一个map集合。

      *默认:array = 数组

      *使用@Param注解改变map集合的默认key的名称

void deleteByIds(@Param("ids") int[] ids)
//mybatis会将数组参数,封装成一个map集合。
//separator用分隔符分开 示例中用,分隔多个需要删除的id
//foreach是遍历整个数组
<delete id="deleteByIds">
/*    
    delete from tb_brand where id 
    in
    	<foreach collection="arrays" item="id" separator=",",open="(",close=")">
    		#{id}
    	</foreach>
    	;
*/
/*   
    delete from tb_brand where id 
    in(
    	<foreach collection="ids" item="id" separator=",">
    		#{id}
    	</foreach>
    	);
*/
    delete from tb_brand where id 
    in
    	<foreach collection="ids" item="id" seperator=",",open="(",close=")">
    		#{id}
    	</foreach>
    	;
</delete>

注解开发

  • 查询@Select
@Select("select * from tb user where id = #{id}")
public User selectByld(int id)

添加修改删除操作与查询类似

  • 添加@Insert
  • 修改@Update
  • 删除@Delete

复杂的操作使用xml,简单的语句使用注解

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值