Mybatis学习笔记(一)

一、mapper标签:

<mapper namespace = "对应接口">

例如:<mapper namespace = "com.demo.dao.StudentDao">

二、查询语句 :

<select id="对应接口的方法名" parameterType = "传入参数类型" resultType="查询返回类型"</select>

例如:

<select id="selectStudentById" parameterType = "java.lang.Integer" resultType="com.demo.domain.Student">

select id,name from student where id = #{id}

</select>

三、parameterType

Mybatis框架可以通过反射,找到输入参数类型,一般可以省略

四、@Param注解(重点)

当需要传入多个参数时,可以使用@Param命名参数

例:

public List<Student> selectMulitParam(@Param("myname")String name,@Param(myage)Integer age)

<select id="selectMulitParam" resultType="com.demo.domain.Student">

select id,name,age from student where name = #{myname} and age = #{myage}

</select>

五、使用对象传参(重点)

<select id="selectMulitClassRoom" resultType="com.demo.domain.ClassRoom">

select id,name from classroom where studentName = #{与传入对象参数名相同} and studentAge = #{与传入对象参数名相同}

</select>

例:

class Student{

private String studentName;

private int studentAge;

......

}

public List<Student> selectMulitClassRoom(Student student)

<select id="selectMulitClassRoom" resultType="com.demo.domain.ClassRoom">

select id,name from classroom where studentName = #{studentName} and studentAge = #{studentAge}

</select>

六、按位置传参

例:

public List<Student> selectStudent(String name,Integer age)

<select id="selectStudent" resultType="com.demo.domain.Student">

select id,name,age from student where name = #{arg0} and age = #{arg1}

</select>

name,age ---->#{arg0},#{arg1}位置从左到右一一对应

七、map传参(不建议使用)

<select id="selectMultiByMap" resultType="com.demo.domain.Student">

select id,name,age from student where name = #{key} and age = #{key}

</select>

例:

List<Student>selectMultiByMap(Map<String.Object> map)

Map<String.Object> map = new HashMap<>();

map.put("myname","张三");

map.put("age",30);

<select id="selectMultiByMap" resultType="com.demo.domain.Student">

select id,name,age from student where name = #{myname} and age = #{age}

</select>

八、#和$的区别

1.#:占位符,告诉mybatis使用实际的参数值代替。并使用PrepareStatement对象执行sql语句,

#{...}代替sql语句的"?",这样子做更安全,更改迅速,通常也是首选做法。

2.$:字符串替换,告诉mybatis使用$包含的"字符串"替换所在位置。使用Statement把sql语句和${...}的内容连接起来,主要用在替换表名,列名,不同列排序等操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值