通过xml方式使用
通过这种方式使用,我们是需要mapper.java和mapper.xml文件的。而SQL语句是在mapper.xml文件之中。
查询操作
使用select标签
返回结果集可以使用resultType和resultMap两种,对于数据库表的列名和java映射类的属性名如果一致时,可以使用resultType和resultMap处理都可以。
<!--
select标签:查询操作
id属性:statement的id,用于表示定义的SQL,在同一个命名空间中id是不允许重复的
#{XXX}:输入参数的占位符,避免SQL注入
parameterType:输入参数类型
resultType:指定结果集类型
-->
<select id="selectStudentById" parameterType="int" resultType="com.tulun.test.pojo.Student" >
select * from Student where SID = #{id}
</select>
如果表列名和类属性存在不一致的情况时,我们需要使用result Map来手动实现映射过程。
<resultMap type="student" id="studentResultMap">
<!-- 定义主键 ,非常重要。如果是多个字段,则定义多个id -->
<!-- property:主键在pojo中的属性名 --> <!-- column:主键在数据库中的列名 -->
<id property="id" column="SID" />
<!-- 定义普通属性 -->
<result property="Sname" column="Sname" />
//省略
对于单个对应的映射还是多个对象的映射,resultType和resultMap只关注映射的对象类型,查询操作会根据是单个对象则选取selectOne方法执行,返回多个对象则使用selectList方法来执行。
插入和修改的写法
<insert id="addStudent" parameterType="student">
insert into Student (SID,Sname,Sage,Ssex) values
(#{id},#{Sname},#{Sage},#{Ssex} )
</insert>
<update id="updateNameById" >
update Student set Sname =#{name} where SID = #{id}
</update>
可以看到在修改操作中存在多参数传递问题,通过参数传递的name是不能被mybatis识别的,mybatis中多参数提供的有0,1,parm1和parm2作为参数。
为了解决这种问题,可以使用@Param注解对参数进行绑定。
public int updateNameById(@Param("name") String name,@Param("id") Integer id);
基于xml形式需要遵循一定规则:
- 1、xml配置文件中的命名空间和指向接口文件的地址(全路径)
- 2、mapper.java接口文件中的方法名和mapper.xml中Statement的id保持一致
- 3、mapper.java接口中方法参数和mapper.xml中Statement的parameterType或parameterMap的类型一致
- 4、mapper.java接口中方法返回值类型和mapper.xml中mapper.xml文件中Statement的resultType或resultMap类型一致
通过注解方法
首先,需要创建对应表的pojo类,我们在前面也做过类似操作。给定mapper.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">
<!--mapper根标签 namespace,命令空间:保证命名空间唯一,一般是对应的mapper.java的包全路径-->
<mapper namespace="com.tulun.mapper.UserMapper">
</mapper>
接口文件,SQL都在注解上,且注解在mapper.java文件中
/**
* @Select 注解即xml配置文件中select标签
*
* @Results注解和xml 配置文件中ResultMap标签使用类似
*/
@Results(id = "userResult",
value = {
@Result(column = "id" ,property = "id"),
@Result(column = "name",property = "name"),
@Result(column = "passwd", property = "passwd")
})
@Select({"select * from user where id = #{id}"})
public User selectUserById(Integer id);
@Insert("insert into user (name,passwd) values(#{name},#{passwd})")
public int addUser(User user);
不同的操作使用不同的注解即可。
我们可以看到sql语句中使用了#{}来代替参数,其实也有另一种写法
。
这
两
种
写
法
的
区
别
其
实
和
当
时
S
t
a
t
e
m
e
n
t
和
p
r
a
p
e
r
t
e
S
t
a
t
e
m
e
n
t
的
区
别
相
似
。
{}。 这两种写法的区别其实和当时Statement和praperteStatement的区别相似。
。这两种写法的区别其实和当时Statement和praperteStatement的区别相似。{}是直接进行参数拼接,不能解决SQL注入问题。#{}会进行被替换。可以解决SQL注入问题,较安全。