mybatis框架

一、mybatis

mybits介绍

MyBatis 是一款优秀的持久层框架
特征:
1、支持自定义 SQL(非自定义SQL:hebineate)、存储过程以及高级映射。
2、MyBatis解决JDBC 代码以及设置参数和获取结果集的工作。
3、MyBatis通过XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录

mybatis原理

在这里插入图片描述

二、mybits的应用

1.配置

1.在xml文件中引入依赖

        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>

2.全局配置文件(mybatis-config.xml)

以test_tulun库为例:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--根标签-->
<configuration>
    
    <!--配置数据源-->
    <environments default="development">
        <!--id:环境的唯一标识-->
        <environment id="development">
            <!--事务管理器-->
            <transactionManager type="JDBC"></transactionManager>
            <!--数据源类型-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test_tulun"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
            
        </environment>
    </environments>
</configuration>

3.定义一个pojo类

/**
 * 和数据库中的Student表对应
 */
public class Student {
    private Integer sid;
    private String sname;
    private String sex;
    private Integer sage;
  //省略的getter和setter方法,toString()方法
}

4.Mapper接口文件(StudentMapper.java)

public interface StudentMapper {
    public Student selectStudentById(Integer id); 
}

5.配置mapper.xml文件(StudentMapper.xml)

mapper.xml配置文件中是配置SQL语句的,mapper接口文件中每一个方法在mapper.xml文件中对应一个唯一的Statement(sql)

<?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.StudentMapper">

    <!--
    selectStudentById
    select * from Student where SID = XXX
    -->

    <!--
    select标签:查询操作
    id属性:statement的id,用于表示定义的SQL,在同一个命名空间中id是不允许重复的
     #{XXX}:输入参数的占位符,避免SQL注入
     parameterType:输入参数类型
     resultType:指定结果集类型
    -->
    <select id="selectStudentById" parameterType="int" resultType="com.tulun.pojo.Student" >
        select * from Student where SID = #{id}
    </select>
</mapper>

6.修改全局配置文件

在mybatis-config.xml中引入配置文件

    <!--引入mapper配置文件-->
    <mappers>
        <mapper resource="mapper/StudentMapper.xml"/>
    </mappers>

7.执行查询操作

在StudentMapper.xml文件中添加

<!--
    select标签:查询操作
    id属性:statement的id,用于表示定义的SQL,在同一个命名空间中id是不允许重复的
     #{XXX}:输入参数的占位符,避免SQL注入
     parameterType:输入参数类型
     resultType:指定结果集类型
    -->
    <select id="selectStudentById" parameterType="int" resultType="Integer " >
        select * from Student where SID = #{id}
    </select>

在test下生成一个测试类
在这里插入图片描述

          //mybatis的配置文件
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //通过反射机制来获取到mapper实例
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            Student student = mapper.selectStudentById(10);
            System.out.println(student);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

8.总结:mybatis的使用步骤:

1、配置mybatis-config.xml全局配置文件(数据源、外部mapper)
2、创建SQLSessionFactory
3、通过SQLSessionFactory来创建SQLSession
4、通过SQLSession进行CRUD操作
5、关闭会话 SQLSession.close()操作

三、mybatis的使用

1.通过xml方式使用

需要mapper.java和mapper.xml
SQL写在我们mapper.xml文件中

查询操作

使用select标签
返回结果集可以使用resultType和resultMap两种
对于数据库表的列名和java映射类的属性名如果一致时,可以使用resultType和resultMap处理都可以
如果表列名和类属性名存在不一致时,需要使用resultMap来手动实现映射过程,如下:

   <!--
    resultMap标签是自定义返回结果,当返回结果指定为resultMap时使用标签
    id属性:取名字 select操作时结果集通过resultMap属性指定时使用该id属性
    type属性:要映射的java的全路径

    id/result时对结果的自定义映射
    id标签是主键使用该标签,结果集中只能设定一个id标签
    result处理非主键标签
-->
<resultMap id="studentResult" type="com.tulun.test.mybatis.Pojo.Student">
<!--    <id property="" column=""/>-->
    <result column="sid" property="id"/>
    <result column="sname" property="sname"/>
    <result column="sex" property="sex"/>
    <result column="sage" property="sage"/>

</resultMap>

对于单个对应的映射还是多个对象的映射,resultType和resultMap只关注映射的对象类型,查询操作会根据是单个对象则选取selectOne方法执行,返回多个对象则使用selectList方法来执行

插入对象

<insert id="addStudent" parameterType="student">
        insert into Student (sid,sname,sex,sage) values
        (#{sid},#{sname},#{sex},#{sage} )
    </insert>

多参数传递:

多参数接口:

public int updateNameById(String name,Integer id);

通过参数传递的name是不能被mybatis识别的,mybatis中多参数提供的有0,1,parm1和parm2作为参数,
为了解决这种多参数传递可以使用@Param注解来对参数进行绑定

public int updateNameById(@Param("name") String name,@Param("id") Integer id);

通过参数形式底层是通过map的实现方式进行参数传递,
其中map的key即为注解中的名称,value即为名称对应的值

基于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类型一致

2.通过注解方法

创建表对应的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.test.mybatis.mapper.UserMapper">

</mapper>

全局配置文件中引入mapper.xml

    <mappers>
        <mapper resource="mapper/UserMapper.xml"/>
        </mappers>

接口文件,SQL都在注解上,且注解存在mapper.java文件

public interface UserMapper {
    /**
     *@Select 注解即xml文件中select标签
     */
    //类似与resultMap
    //Results不是全局调用的,如果需要则要在相应的注解语句前加上
    @Results(id = "userResult",value = {
            @Result (column = "tid" ,property = "id"),
            @Result (column = "tname",property = "tname")

    })
    @Select("select * from teacher where tid= #{id}")
    public User selectUserById(Integer id);
    @Insert("insert into teacher values(#{id},#{tname})")
    public  int addUser(User user);
}

#{}和${}区别

1.#{}在执行时将其替换为?,且sql和参数分别传递,类似于JDBC中的PreparedStatement
2.${}方法参数的传递是通过OGNL表达式进行解析的,需要调用参数中的getter方法,因此参数必须右getter存在
${}的参数是直接拼接在sql语句上的,相当于JDBC中的statem
3.安全性: 使用#{}可以放在sql注入问题

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值