MyBatis是一个持久层框架,不同于hibernate的是,它的sql语句需要手动来写,这样开发起来更加的灵活。

Mybatis的执行过程:

SqlMapConfig.xml----->SqlSessionFactory----->SqlSession---->Executor(执行器)---->Mapped Statement(底层分装对象)------>MySql。

在SqlMapConfig.xml中需要配置具体数据源,并且会加载具体的xxxMapper.xml

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

</mappers>

UserMapper.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="com.mapper.UserMapper">
    <!--一个查询过程-->
    <select id="findUserById" parameterType="int" resultType="com.domain.User">
        select * from user where id = #{id}
    </select>

</mapper>

parameterType:输入参数类型

resultType:输出参数类型

#{}:占位符号

${}:拼接符号(容易引起sql注入,不建议使用)。

返回自增id:

<!--useGeneratedKeys="true"表明使用数据库自动生成的主键,
      keyColumn="id"指定Student表中主键列,keyProperty="id"
            表明当插入记录后,会把数据库生成的主键值设置到Student对象
            的id属性中,也就是说,它指定与Student表中的主键列对应的
      Student实体类中的属性是id这个属性-->
    <insert id="add" useGeneratedKeys="true"
     keyColumn="id" keyProperty="id" parameterType="com.domain.User">
        insert into user(name, password, email, age) values(#{name}, #{password}, #{email}, #{age})
    </insert>

注:正在学习,自己做的一些笔记