Mybatis使用

一、接口绑定实现方式

mybatis中接口绑定主要有两种实现方式

● 通过注解绑定:就是在接口的方法上加上@Select、@update等注解,里面包含SQL语句进行绑定

● 通过XML里面写SQL进行绑定,需要指定xml映射文件里的namespace必须为接口的全路径
语句比较简单时,使用注解绑定,当SQL语句比较复杂是,用xml绑定,一般使用xml比较多

二、XML方式的用法

mybatis的强大之处在于自定义SQL语句,映射器的xml文件方式相比JDBC简单,节省代码量

2.1使用步骤

  1. 创建Mapper.Java接口文件
public interface StudentMapper {     
Student selectStudentById(Integer sid); 
}
  1. 创建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">
<!--根标签  namespace命令空间:给定接口文件的全路径--> 
<mapper namespace="com.tulun.Mybatis.mapper.StudentMapper">     
<select id="selectStudentById"  parameterType="int" resultType="student">         
select * from student where SID =#{sid}     
</select> 
</mapper>
  1. 在全局配置文件中配置映射路径
<mappers>       
<mapper resource="mapper/StudentMapper.xml"/> 
</mappers>

2.2 XML开发方式规范

  • 在mapper.xml中namespace命令空间等于Mapper接口的全路径名

  • Mapper.java接口中的方法名和Mapper.xml中的Statement的Id一致

  • Mapper.java接口中方法的参数类型和Mapper.xml中parameterType的指定类型一致

  • Mapper.java接口中方法的返回值类型和Mapper.xml中的resultType指定的类型一致

2.3 标签介绍

2.3.1 select标签
返回值以resultMap为例讲解如下:
<!--          
id属性:必填,表示取名称,可以随便给定     
type属性:必填,指定显性映射的Java类的全限定名       
id标签:指定主键映射关系 id标签一般使用一次指定主键即可      
result标签:指定非主属性映射关系,可以多次使用        
property属性:指定Java类中属性名(必填)         
column属性:指定数据库中的属性名称(必填)         
jdbcType属性:指定数据库中当前属性类型(选填)         
javaType属性:指定Java类中属性类型(选填)         
typeHandler属性:类型Handler,如果是有自定义类型处理器需要在这里指定自定义类型处理器的全限定名(选填)     --> 
<resultMap id="studentMap" type="student">         
  <id property="SID" column="SID" />         
  <result property="name" column="Sname" />         
  <result property="Ssex" column="Ssex" />         
  <result property="Sage" column="Sage" />     
</resultMap>
<!-- 注:resultType和resultMap区别
当resultType无法完成某些自动字段映射时,需要resultMap进行显性映射关系配置     
resultMap标签主要是用来显性指定返回值映射关系-->

在这里插入图片描述
返回是结果集

//查询所有数据
ListselectAllStudents();

<select id="selectAllStudents" resultType="MyBatis.pojo.Student">
        select * from student
 </select>

不管是返回一个结果还是多个结果集,返回类型和结果数量是无关的。

resultMap和resultType的区别?
resultMap和resultType都是指定返回参数类型,类型可以是pojo类全限定名或别名
resultType可以完成自动映射过程,但是对于字段不一致时是无法完成字段映射的,如果字段完全一致优先选取resultType
resultMap是可以显性完成映射过程,对于字段不一致时能够完成映射,字段不一致优先选取resultMap进行映射

如果数据库属性名和Java的字段名不一致时还能创建出映射对象吗?不可以
如果数据库属性名和Java的字段名只存在一个相同的,可以创建出对象吗?都可以创建

2.3.2 insert标签
//插入数据
    /**
     * 插入数据返回类型可以是void、int类型(表示影响数据行数,如果大于0,说明修改成功)
     * @param id
     * @return
     */
    int insertStudent(Student student);
<!--
    insert标签表示插入数据
    id:是Statementid,在命名空间具有唯一性,和方法名保持一致
    parameterType/parameterType属性:指定入参的类型,可以是类的全限定名或者别名
    flushCache属性:参数为true或者false,默认为true,用来清除一级缓存和二级缓存
    keyProperty:指定pojo类中主键属性名
    useGeneratedKeys属性:默认为false或者是true
    如果是true,会采用数据自增主键  auto_increment完整性约束
    keyColumn:表示数据库中主键的属性名,在update和insert中有效

    无返回类型指定,如果接口方法返回为int自动给定值
    -->
    <insert id="insertStudent" keyColumn="" keyProperty="" useGeneratedKeys="true" parameterType="MyBatis.pojo.Student">
        insert into
        student(SID,Sname,Sage,Ssex)
        values
        (#{SID},#{name},#{Sage},#{Ssex})
    </insert>
2.3.3 多个参数的接口问题

给定需求:通过id来修改name
接口:

 //更新用户姓名
    int updateNameByID(Integer id,String name);
<update id="updateNameByID" parameterType="java.lang.String">
        update Student set Sname = #{name} where SID= #{id}
    </update>

直接调用抛出BindingException异常:
在这里插入图片描述
这个错误表示,XML可用的参数只有0,1,param1,param2,没有id和name。0和1,param1和param2都是mybatis根据参数位置自定义名字,如果将参数中#{name}参数修改为#{0}或者#{param1},将#{id}参数改为#{1}或者#{param2},这个方法即可调用,但是这样的参数不易立即建立它们之间关系。
解决方案:通过给参数配置@Param注解,mybatis会自动将参数封装为Map类型,@Param注解值作为map中的key,其对应的参数实际值作为value,这样SQL中会通过解析map来获取值

修改如下:

//更新用户姓名
    int updateNameByID(@Param("id") Integer id, @Param("name") String name);

三、注解方式的用法

注解形式是直接将SQL写在接口方法上
优势:效率较高
缺点:SQL有变动时需要重新编译代码
在mybatis注解的SQL中,基本的注解:@Select、@Update、@Delete、@Insert

以user表为例讲解

注解实现步骤

1、给定pojo类

public class User {
    private Integer id;
    private String name;
    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

2、给定mapper.java接口

public interface UserMapper {    
}

3、在配置文件中指定文件映射位置

<mapper class="MyBatis.mapper.UserMapper"/>

验证注解

@select注解

@select注解类似于xml中的select标签
当字段无法映射时,通过@Result注解完成显性映射

/**
     * 在mybatis的早期版本:3.3.0之前版本@Results是不能共用的
     * 在mybatis的3.3.1之后的版本@Results增加了id属性,可以通过id共用一个Result结果
     * 
     * @Results和XML形式中resultMap标签类似
     */
    
    @Results(id = "userMap",value = {
            @Result(property = "id",column = "id",id = true),
            @Result(property = "name",column = "name"),
            @Result(property = "password",column = "password")
    })
@Insert注解
/**
     * 插入数据
     * @Insert表示插入
     * @Inserthe和XML中的insert标签类似
     * 采用数据库自增主键时使用@Options注解,其中有useGeneratedKeys属性,设置为true
     */
    @Options(useGeneratedKeys = true,keyColumn = "id")
    @Insert("insert into user(name,password) values(#{name},#{password})")
    int insertUser(User user);
@Update注解
@Delete注解
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值