Mybatis的两种用法:
- 使用注解@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);
- 使用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));
}