参数传递
parameterType属性
作用:在标签属性中控制参数类型
参数获取
-
#{}获取
(1)索引,#{0},#{param1}表示第一个参数
只有一个基本数据类型或String的参数#{}内容任意值
(2)对象,#{属性名}
(3)map,#{key} -
#{}和$ {}的区别
(1)#()使用预编译,?作占位符
(2)$ ()使用字符串拼接,$(0)表示传递数字0
接口绑定
mybatis将xml文件生成的实现类与接口绑定,从而实现通过接口进行调用
1.接口名与xml文件中namespace相同
接口中方法名与xml文件内标签的id属 性相同
接口中方法多参,可以省略parameterType
com.test.mapper包内新建接口
public interface PeopleMapper {
List<People> selAll();
}
<mapper namespace="com.test.PeopleMapper">
<select id="selAll" resultType="People">
select * from People where name=#{0}and age=#{1}
</select>
</mapper>
2.mybatis.xml使用扫描接口和xml
<mappers>
<package name="com.test.mapper"/>
</mappers>
typeAliases别名
- 类起别名
<typeAliases>
<typeAlias type="pojo.People"
alias="peo"/>
</typeAliases>
- 包起别名
<typeAliases>
<package name="pojo" />
</typeAliases>
- 系统内置别名
类型小写 Map:map
新增,删除,修改
事务提交
1.默认关闭了JDBC的自动提交
2.使用session.commit()提交事务
3.使用openSession(true)开启自动提交
4.执行openSession()时,创建sqlsession并创建Transaction对象
代码
<insert id="ins" parameterType="People">
insert into people values(default,#{name},#{age})
</insert>
<update id="upd" parameterType="People">
update people set name = #{name} where id = #{id}
</update>
<delete id="del" parameterType="int">
delete from people where id = #{0}
</delete>
//JDBC层使用excuteupdate,成功返回值为1
int index = session.insert("a.b.ins", p);
//int index = session.update("a.b.upd", peo);
//int index= session.delete("a.b.del",3);
if(index>0){
System.out.println("成功");
}else{
System.out.println("失败");
}
session.commit();