Mybatis的两种用法学习笔记

Mybatis的两种用法:

  1. 使用注解@select @insert @delete @update在方法上,注解内写上sql语句,需要输入的参数用#{}表示,然后用方法参数传入,方法参数可以是Java bean对象,体会自动匹配bean对象的属性到sql语句里,比如:

//当有两个参数的时候,参数前要加@Param(参数名),参数名要和#{}里的名字一样

//一个参数的时候不需要加,因为1对1不会出错,2对2的时候,你需要告诉系统哪个参数对应哪个变量

@Update("update t_user set password=#{pwd} where id = #{id}")

//public Integer updatePassword(User user);

public Integer updatePassword(@Param("pwd")String password,@Param("id")int id);

 

  1. 使用xml注解,xml可以处理复杂的batis映射,比如动态sql语句

 2.1在resource文件夹创建xml文件

 <?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper

  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

  <!--namespace是接口所在的全限定名  -->

<mapper namespace="cn.tedu.mapper.UserMapper" >

<!-- id是方法名 -->

<delete id="deleteByIds">

delete from t_user where id in(

<!-- collection是传入参数的类型,数组和可变长度参数是array,集合是list,item是变量名,separator是分隔符,#{}表示传入参数 -->

<foreach collection="array" item="id" separator=",">

#{id}

</foreach>

)

</delete>

</mapper>

2.2在sqlsessionfactory中配置

mapperlocation的位置使用properties文件传入,方便以后地址变了不需要改代码,properties用${}传入数据

@Bean

public SqlSessionFactory sqlSessionFactory(DataSource dataSource ,

@Value("${mybatis.mapper.location}")

Resource[] mapperLocations) throws Exception {

SqlSessionFactoryBean bean = new SqlSessionFactoryBean();

bean.setDataSource(dataSource);

bean.setMapperLocations(mapperLocations);

return bean.getObject();

}

}

 

2.3直接Test里试验即可

@Test

public void tesedeletexml() {

UserMapper mapper = ctx.getBean("userMapper",UserMapper.class);

System.out.println(mapper.deleteByIds(1,4,6));

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值