MyBatis学习总结

MyBatis学习总结(1)

1.JDBC缺点: 硬编码(注册驱动,获取链接;SQL语句)
操作繁琐(手动设置参数;手动封装结果集)
2.MyBatis的简化:将注册驱动、SQL语句写到配置文件中去
各类参数自动执行(一行代码解决)(例如selectList)
3.MyBatis操作流程:
(1)创建数据库表,添加数据
(2)创建模块,导入坐标
(3)编写MyBatis核心配置文件–>替换连接信息,解决硬编码问题
(4)编写SQL映射文件–>统一管理sql语句,解决硬编码问题
(5)编码: 1.定义POJO类
2.加载核心配置文件,获取SqlSessionFactory对象 //去官网复制,更改一下文件路径

String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	3.获取SqkSession对象,然后执行SQL语句
		SqlSession sqlSession = sqlSessionFactory.openSession();
		
		List<user> users = sqlSession.selectList("test.selectAll");//执行SQL语句
        System.out.println(users);		//打印结果

	4.释放资源
	    sqlSession.close();

4.Mapper代理开发: //创建Mapper接口Java Class类型选择Interface
(1)定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下
(2)设置SQL映射文件的namespace属性为Mapper接口全限定名
(3)在Mapper接口中定义方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回值类型一致
(4)编码: 1.通过SqlSession的getMapper方法获取Mapper接口
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
2.调用对应方法完成sql的执行
List users = mapper.selectAll();
5.如果Mapper接口名称和SQL映射文件名称相同,并在同一目录下,则可以使用包扫描的方式简化SQL映射文件的加载

<mappers>
		<package name = "com.itheima.mapper"/>	//直接将mapper下面所有的文件自动加载并自动挑选
	</mappers>

6.MyBatis起类型别名:指定一个包名,MyBatis会在包名下面搜索需要的Java Bean,每一个在包domain.blog中的JavaBean,在没有注解的情况下,会使用Bean的首字母小写的非限定类名来作为它的别名。比如domain.blog.Author的别名为 author;若有注解,则别名为其注解值。

<typeAliases>
	  <package name="domain.blog"/>
	</typeAliases>

7.MyBatis核心配置文件在配置时,各个标签需要遵守前后顺序来配置
8.Mapper代理开发中利用配置文件完成增删改查步骤:
(1)编写接口方法:Mapper接口:
判断参数参数;
结果:List<对象>;
(2)编写SQL语句:SQL映射文件:
(3)执行方法,测试
9.具体实现代码:

1)获取SqlSessionFactoryString resource = "mybatis-config.xml";
    
    InputStream inputStream = Resources.getResourceAsStream(resource);
    
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);2)获取SqlSession对象:
	SqlSession sqlSession = sqlSessionFactory.openSession();3)获取Mapper接口的代理对象:
	UserMapper mapper = sqlSession.getMapper(UserMapper.class);4)执行方法:
	List<user> users = mapper.selectAll();

    System.out.println(users);5)释放资源:
	sqlSession.close();

10.数据库表的字段名称和实体类的属性名称如果不一样,则不能自动封装数据,解决方法:
(1)给名称不同的列起一个与实体类的属性名称相同的别名:select id,brand_name as brandName from XX;
缺点是每次查询都要重新定义一次别名;可以使用sql片段来解决(缺点是不灵活):

<sql id = "brand_column">
		id,brand_name as brandName,company_name as companyName,ordered,description,status
	</sql>

	
	<select id="selectAll" resultType="brand">
	    select 
	    	<include refid = "brand_column" />
	    from tb_brand;
    </select>

(2)常用方法:resultMap
使用方式:
1.定义标签
2.在标签中,使用resultMap属性来替换之前的resultType属性

	id:完成主键字段的映射
		column:表的列名
		property:实体类的属性名
	result:完成一般字段的映射
		column:表的列名
		property:实体类的属性名

<result column = "brand_name" property = "brandName" />
<result column = "company_name" property = "companyName" />
<select id="selectAll" resultMap="brandResultMap">
    select * from tb_brand;
</select>

11.参数占位符:
(1)#{}:会将其中的对象替换为?,能防止SQL注入
(2)KaTeX parse error: Expected 'EOF', got '#' at position 41: …(3)使用参数传递的时候可以用#̲{};表名或者列名不固定的情况…{}
12.参数类型:parameterType:通常省略
13.特殊字符处理:
(1)转义字符:例如xml中不让写< ,可以用&lt代替<
(2)CDATA区:例如小于号<,输入CD回车,创建CDATA区:
<![CDATA[ < //CDATA区内填小于号 ]]>
14.多条件查询三种方法:参数接收:
(1)散装参数:如果方法中有多个参数,需要使用@Param(“SQL参数占位符名称”)

List<Brand> selectByCondition(@Param("status")int status,@Param("companyName")String companyName,@Param("brandName")String brandName);
//接收参数
int status = 1;
String companyName = "华为";
String brandName = "华为";

//处理参数
companyName = "%" + companyName + "%";
brandName = "%" + brandName + "%";		//下面是获取SqlSessionFactory等一系列操作

<select id="selectByCondition" resultMap="brandResultMap">
    select * 
    from tb_brand
    where status = #{status}
    	and company_name like #{companyName}	//模糊查询
    	and brand_name like #{brandName};
</select>

List<Brand> brands = brandMapper.selectByCondition(status,companyName,brandName);//执行

(2)对象参数:实体类的属性名称要和SQL参数占位符名称一致
List selectByCondition(Brand,brand);
对象参数比散装参数要多一步封装对象的过程,要把参数都封装到对象中去然后进行处理

Brand brand = new Brand();
	brand,setXxx(xxx);
List<Brand> brands = brandMapper.selectByCondition(brand);		//执行

(3)map集合参数:保证SQL中的参数名和map集合的键的名称对应上

List<Brand> selectByCondition(Map,map);
	Map map = new HashMap();
	map.put("status",status);
	map.put("companyName",companyName);
	map.put("brandName",brandName);
List<Brand> brands = brandMapper.selectByCondition(map);		//执行

15.多条件-动态条件查询:SQL语句会随着用户的输入或外部条件的变化而变化(MyBatis对动态SQL有支撑)
即输入一个或两个数据时也可以查询相对应的对象

<select id="selectByCondition" resultMap="brandResultMap">
        select * 
        from tb_brand
        /*where
        	1 = 1 */	//可以用where标签来替代where关键字
        <where>
    		<if test = "status != null">
    			and status = #{status}
    		</if>
    		<if test = "companyName != null and companyName != '' ">
    			and company_name like #{companyName}	//模糊查询
    		</if>

    		<if test = "brandName != null and brandName != '' "> //不为null或空字符串
    		    and brand_name like #{brandName};
    		</if>
    	</where>
    </select>

16.单条件-动态条件查询:从多个条件中选择一个,利用choose(when,otherwise):选择,类似于switch

<select id="selectByConditionSingle" resultMap="brandResultMap">
    select * 
    from tb_brand
    where
    <choose>			//类似于switch
		<when test = "status != null">
			tatus = #{status}
		</when>			//类似于case
		<when test = "companyName != null and companyName != '' ">
			company_name like #{companyName}	//模糊查询
		</when>

		<when test = "brandName != null and brandName != '' "> //不为null或空字符串
		    brand_name like #{brandName};
		</when>
		<otherwise>		//类似于default;也可以用where标签来处理,省去了otherwise
			1 = 1
		</otherwise>
	</choose>
</select>

17.MyBatis执行添加操作时,默认会将事务打开,也就是在代码执行完成之后要进行提交:
sqlSession.commit();
或者在第二步获取SqlSession对象时填入true:
SqlSession sqlSession = sqlSessionFactory.openSession(true); //关闭事务
18.添加-主键返回 例如需要在添加完订单之后返回所属订单id
(可以添加 useGenerateKeys = “true” keyProperty = “id”)

<insert id = "addOrder" useGenerateKeys = "true" keyProperty = "id">
		insert into tb_order(xxx,xxx,xxx)
		values (#{xxx},#{xxx},#{xxx});
	</insert>

19.实现动态添加可以通过和动态查询一样原理的 方法来完成,并且set关键字要改为set标签来使用!!否则会出bug
20.update添加更新的各个列名,最后一列末尾不需要加逗号!
21.批量删除–用到in()
Mapper接口:void deleteByIds(@Param(“ids”)int[] ids); //传入id数组

22.MyBatis会将数组参数默认封装为一个Map集合,这个数组默认用array存储,即array = 数组
23.MyBatis参数传递:MyBatis接口方法中可以接受各种各样的参数,MyBatis底层对于这些参数进行不同的封装处理方式:
(1)单个参数:
1.POJO类型:直接使用,属性名和参数占位符名称一致,MyBatis不会将POJO类型进行封装,所以也不需要使用@Param注解,直接使用就可以
2.Map集合: 直接使用,键名和参数占位符名称一致
3.Collection: 封装为Map集合,用@Param注解替换Map集合中默认的arg键名
map.put(“arg0”,collection集合)
map.put(“collection”,collection集合)
4.List: 封装为Map集合,用@Param注解替换Map集合中默认的arg键名
map.put(“arg0”,list集合)
map.put(“collection”,list集合)
map.put(“list”,list集合)
5.Array: 封装为Map集合,用@Param注解替换Map集合中默认的arg键名
map.put(“arg0”,数组)
map.put(“array”,数组)
6.其他类型:直接使用

(2)多个参数:多个参数主要用@Param:用@Param注解替换Map集合中默认的arg键名:
User select(@Param(“username”)String username,@Param(“password”)String password);

24.注意:不要用默认的名称,直接使用@Param注解替换arg0,并使用修稿后的名称来获取值,可读性高!!!
25.MyBatis提供了ParamNameResolver类来进行参数封装,多个参数传进来之后会被封装成为Map集合:
map.put(“arg0”,参数值1)
map.put(“param1”,参数值1) //如果不用@param,可以通过arg或者param来调用相应参数(不推荐)
map.put(“arg1”,参数值2)
map.put(“param2”,参数值2)
25.配置文件完成增删改查就是将操作写到xml文件里去,而注解完成增删改查就是把操作写成注解。使用注解开发会比配置文件开发更加方便,一般用于实现简单功能,复杂功能还是要用配置文件
26.注解开发:
@Select(“select * from tb_user where id = #{id}”)
public User selectById(int id); //共有四个注解:@Select,@Insert,@Update,@Delete

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大锋锋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值