学习mybatis
1 #{}和${}的区别是什么?
• 是 P r o p e r t i e s 文件中的变量占位符,它可以用于标签属性值和 s q l 内部,属于静态文本替换,比如 {}是 Properties 文件中的变量占位符,它可以用于标签属性值和 sql 内部,属于静态文本替换,比如 是Properties文件中的变量占位符,它可以用于标签属性值和sql内部,属于静态文本替换,比如{driver}会被静态替换为com.mysql.jdbc.Driver。
• #{}是 sql 的参数占位符,Mybatis 会将 sql 中的#{}替换为?号,在 sql 执行前会使用 PreparedStatement 的参数设置方法,按序给 sql 的?号占位符设置参数值,比如 ps.setInt(0, parameterValue),#{item.name} 的取值方式为使用反射从参数对象中获取 item 对象的 name 属性值,相当于 param.getItem().getName()。
2 标签
2.1 select
查询学生,根据id
<select id="getStudent" parameterType="String" resultMap="studentResultMap">
SELECT ST.STUDENT_ID,
ST.STUDENT_NAME,
ST.STUDENT_SEX,
ST.STUDENT_BIRTHDAY,
ST.CLASS_ID
FROM STUDENT_TBL ST
WHERE ST.STUDENT_ID = #{studentID}
</select>
2.2 insert
2.2.1 简单例子
<insert id="insertStudent" parameterType="StudentEntity">
INSERT INTO STUDENT_TBL (STUDENT_ID,
STUDENT_NAME,
STUDENT_SEX,
STUDENT_BIRTHDAY,
CLASS_ID)
VALUES (#{studentID},
#{studentName},
#{studentSex},
#{studentBirthday},
#{classEntity.classID})
</insert>
2.2.2 返回插入id
insert可以使用数据库支持的自动生成主键策略,设置useGeneratedKeys=”true”,然后把keyProperty 设成对应的列,就搞定了。比如说上面的StudentEntity 使用auto-generated 为id 列生成主键。推荐使用这种用法。
<insert id="insertStudent" parameterType="StudentEntity" useGeneratedKeys="true" keyProperty="studentID">
2.2.3批量插入
方法一:
<insert id="add" parameterType="EStudent">
<foreach collection="list" item="item" index="index" separator=";">
INSERT INTO TStudent(name,age) VALUES(#{item.name}, #{item.age})
</foreach>
</insert>
上述方式相当语句逐条INSERT语句执行,将出现如下问题:
- mapper接口的add方法返回值将是最一条INSERT语句的操作成功的记录数目(就是0或1),而不是所有INSERT语句的操作成功的总记录数目
- 当其中一条不成功时,不会进行整体回滚。
方法二:
<insert id="insertStudentAutoKey" parameterType="java.util.List">
INSERT INTO STUDENT_TBL (STUDENT_NAME,
STUDENT_SEX,
STUDENT_BIRTHDAY,
CLASS_ID)
VALUES
<foreach collection="list" item="item" index="index" separator=",">
( #{item.studentName},#{item.studentSex},#{item.studentBirthday},#{item.classEntity.classID})
</foreach>
</insert>
selectKey
返回插入id还可以使用selectKey元素。下面例子,使用mysql数据库nextval(‘student’)为自定义函数,用来生成一个key。
<insert id="insert" parameterType="SysUser" >
< selectKey keyProperty="id" order="AFTER" resultType="java.lang.string">
select LAST_INSERT_ID() # select LAST_INSERT_ID()
</selectKey>
insert into sys_user
(id, name, email, phone)
values
(#{id},#{name},#{email},#{phone})
</insert>
keyProperty:selectKey 语句生成结果需要设置的属性。
resultType:生成结果类型,MyBatis 允许使用基本的数据类型,包括String 、int类型。
order:可以设成BEFORE 或者AFTER,如果设为BEFORE,那它会先选择主键,然后设置keyProperty,再执行insert语句;如果设为AFTER,它就先运行insert 语句再运行selectKey 语句,通常是insert 语句中内部调用数据库(像Oracle)内嵌的序列机制。
取值范围:BEFORE/AFTER
BEFORE适合使用在设置UUID的情况,AFTER适合使用在返回自增id的情况,两者搭配的语句也不同,BEFORE:SELECT UUID() ,AFTER:SELECT LAST_INSERT_ID();
statementType:像上面的那样, MyBatis 支持STATEMENT,PREPARED和CALLABLE 的语句形式, 对应Statement ,PreparedStatement 和CallableStatement 响应。取值范围:STATEMENT、PREPARED、CALLABLE