mybatis01

作者: 编程_书恨少 | 来源:发表于2018-09-10 18:11 被阅读0次

1. 有了hibernate为什么要使用mybatis

Hibernate: 是一个标准的 ORM 框架(对象关系映射)。学习成本较高,不需要编写sql语句,SQL语句自动生成。对于sql语句的优化,修改比较困难。
应用场景:
适合用于sql语句简单的,效率要求不是特别高的项目。

Mybatis: 专注于sql语句,对象映射和输入输出,都由框架帮你完成,所以属于半 ORM系统,
适用场景:
sql语句逻辑复杂,效率要求特别高的应用。

2. mybatis结构图

Snip20180910_14.png

3. helloMybatis

3.1下载mybatis包

https://github.com/mybatis/mybatis-3/releases

然后导包

3.2书写pojo的User

User

 /**
     *
     */
    private static final long serialVersionUID = 1L;
    private Integer id;
    private String username;// 用户姓名
    private String sex;// 性别
    private String address;// 地址

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }


    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

3.3 书写mapper接口,接口方法需要遵循四个原则

public interface UserMapper {

    //遵循四个原则
    //1.接口 方法名  == User.xml 中 id 名
    //2.返回值类型  与  Mapper.xml文件中返回值类型要一致
    //3.方法的入参类型 与Mapper.xml中入参的类型要一致
    //4.命名空间 绑定此接口
    public User findUserById(Integer id);


    public User findUserByUsername(String username);


    public Integer insertUser(User user);


    public void updateUser(User user);


    public void deleteUserById(int i);

}

3.4 书写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="mapper.UserMapper">

    <!-- 通过ID查询一个用户 -->
    <select id="findUserById" parameterType="Integer" resultType="pojo.User">
        select * from user where id = #{v};
    </select>


    <!-- //根据用户名称模糊查询用户列表
    #{}    select * from user where id = ?    占位符  ? ==  '五'
    ${}    select * from user where username like '%五%'  字符串拼接
     -->
    <select id="findUserByUsername" parameterType="String" resultType="pojo.User">
        select * from user WHERE username LIKE "%"#{v}"%";
    </select>

    <insert id="insertUser" parameterType="pojo.User">
        // 返回插入数据的id
        <selectKey keyProperty="id" resultType="Integer" order="AFTER">
          SELECT LAST_INSERT_ID();
        </selectKey>

        INSERT INTO user (username, address, sex) VALUES (#{username}, #{address}, #{sex});

     </insert>

    <update id="updateUser" parameterType="pojo.User">
        UPDATE user
        SET username = #{username}, address = #{address}, sex = #{sex} WHERE id = #{id};
    </update>

    <delete id="deleteUserById" parameterType="Integer">
        DELETE FROM user WHERE id = #{id}
    </delete>

</mapper>


3.5 测试UserMapperTest

public class UserMapperTest {

    @Test
    public void findUserById() throws IOException {
        //加载核心配置文件
        String resource = "sqlMapConfig.xml";

        InputStream in = Resources.getResourceAsStream(resource);
        //创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        //创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        User user = userMapper.findUserById(1);

        System.out.println(user);
    }

    @Test
    public void testFindUserByUsername() throws IOException {

        //加载核心配置文件
        String resource = "sqlMapConfig.xml";

        InputStream in = Resources.getResourceAsStream(resource);
        //创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        //创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        System.out.println(userMapper.findUserByUsername("张污"));

    }

    @Test
    public void insertUser() throws IOException {

        //加载核心配置文件
        String resource = "sqlMapConfig.xml";

        InputStream in = Resources.getResourceAsStream(resource);
        //创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        //创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();


        User user = new User();
        user.setUsername("阿珍");
        user.setAddress("北京");
        user.setSex("男");

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.insertUser(user);

        sqlSession.commit();

        // 用户保存好之后,获取到用户的id进行其他的后续操作
        System.out.println(user.getId());
    }


    @Test
    public void updateUserById() throws IOException {

        //加载核心配置文件
        String resource = "sqlMapConfig.xml";

        InputStream in = Resources.getResourceAsStream(resource);
        //创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        //创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();


        User user = new User();
        user.setId(1);
        user.setUsername("张三");
        user.setAddress("北京33");
        user.setSex("男33");

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.updateUser(user);

        sqlSession.commit();
    }


    @Test
    public void deleteUserById() throws IOException {

        //加载核心配置文件
        String resource = "sqlMapConfig.xml";

        InputStream in = Resources.getResourceAsStream(resource);
        //创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        //创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();


        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        userMapper.deleteUserById(3);

        sqlSession.commit();
    }


}

4.问题

4.1 关于模糊查询时,中文查不到结果的问题

要将数据库设置成UTF-8的编码

<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://123.206.7.239/xiaobang?characterEncoding=UTF-8" />

相关文章

  • Mybatis01

    1、前言 MyBatis 源于 Apache 的一个开源项目 iBatis,而 iBatis 一词则来源于“int...

  • mybatis01

    1. 有了hibernate为什么要使用mybatis Hibernate: 是一个标准的 ORM 框架(对象关系...

  • MyBatis01

    学习了3种使用方式 案例链接(包含jar包): https://pan.baidu.com/s/1hykf9d2I...

网友评论

      本文标题:mybatis01

      本文链接:https://www.haomeiwen.com/subject/xcolgftx.html