1-----Mybatis简介

Posted 梦想成为DALAO

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1-----Mybatis简介相关的知识,希望对你有一定的参考价值。

没有mybatis

建表

 查询

import java.sql.*;

public class DatabaseTest {

    public static void main(String[] args) throws SQLException, ClassNotFoundException {

        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8", "root", "123456");
        Statement statement = conn.createStatement();
        String sql = "select * from user where id = ?";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setInt(1, 2);
        ResultSet resultSet = preparedStatement.executeQuery();
//        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()){
            System.out.println(resultSet.getInt(1));
            System.out.println(resultSet.getString(2));
            System.out.println(resultSet.getString(3));
        }
    }
}

 

直接给你整懵!

statement与preparedment

个人总结:就是一个端茶送水的店小二。。。将sql语句提交给mysql;并将结果集拿回来。

preparedment是比较高级的店小二,会预编译,而且可以自定义查询值,不像statement每次sql语句都得拼接。

快就完事了preparedment

反正很复杂。

mybatis

简介

  1. 一款优秀的持久层框架。----------------------------就是数据库
  2. 避免几乎所有的JDBC代码和手动设置参数以及获取结果集的过程------------------------------就是全自动呗,不用再自己配statement和preparedment
  3. mybatis可以使用简单的XML或者注解来配置映射原生信息,将接口和Java的实力类相互映射。---------------------------------------数据库中有一个表叫作user,那么java中有一个类叫作user,字段间都相互对应。
  4. 以前叫作ibatis
  5. 现在再github上也有

持久化

数据可以保持很久,就是保存在磁盘中呗。

持久层

完成持久化工作的代码块------->dao(data access object) 数据访问对象

为什么需要mybatis

  • 帮助存数据、取数据

  • 传统太繁琐
  • 半自动的ORM框架(Object Relationship Mapping)----->对象关系映射

优点:简单、灵活、解除sql语句与程序代码的耦合

简单的mybatis程序

mybatis的执行流程

 实体类-----Lombok插件有问题,导不进去

package com.sicheng.entity;


public class User {

    private int id;
    private String name;
    private String pwd;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    public User() {
    }

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

查找类---也就是dao类

就是通过各种姿势查找访问数据库的类

例如:通过主键查找、名字查找、、、、、

package com.sicheng.dao;

import com.sicheng.entity.User;

import java.util.List;

public interface UserMapper {

    List<User> selectUser();
}

Mybatis的配置文件

应该看的懂吧

<?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="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;serverTimezone=GMT%2B8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="com/sicheng/dao/userMapper.xml"/>
    </mappers>
</configuration>

与dao类相互映射的,mapper文件

<?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.sicheng.dao.UserMapper">
    <select id="selectUser" resultType="com.sicheng.entity.User">
        select * from user;
    </select>
</mapper> 

MybatisUtils

用于生产session

package com.sicheng.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static{
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = null;
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSession(){
        return sqlSessionFactory.openSession();
    }
}

Test

import com.sicheng.dao.UserMapper;
import com.sicheng.entity.User;
import com.sicheng.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class MybatisTest {

    @Test
    public void selectUser(){
        SqlSession session = MybatisUtils.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        List<User> users = userMapper.selectUser();
        for (User user :users) {
            System.out.println(user);
        }
    }
}

注意事项

  • Mapper文件当中,一定要写namespace,指明这是哪个dao类的映射文件
  • mapper文件中 id 一定是那个dao类的方法。
  • UseMapper类 和 userMapper配置文件的名字必须保持也一样的哦!!!!!!

 补充知识

xml中的   &amp;   是个啥?

xml当中不能显示的符号 以及 如何进行转义

&lt; < 小于号
&gt > 大于号
&amp &
&apos \' 单引号
&quot " 双引号

 

 

 

 

 

 

第二种方法:

<![CDATA[
   内部的所有内容都会被解析器忽略
]]>

数据库连接中

jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;serverTimezone=GMT%2B8

要写时间区间的,保证安全性?

Resources类

Resources 类为从类路径中加载资源,提供了易于使用的方法。

 

 

所以才在加载时,直接使用mybatis-config.xml这个路径名

 

Resources类的常用情况

  • 从类路径下加载SQL Map配置文件
  • 从类路径加载DAO Manager配置文件
  • 从类路径机在各种.properties文件

Resources类加载一个资源的方式

  • 对于简单的只读文本数据,加载为Reader
  • 对于简单的只读二进制或者文本数据,加载为Stream;
  • 对于读写二进制或文本文件,加载为File.
  • 对于只读的配置文件,加载为Properties
  • 对于只读的通用资源,加载为URL

根据加载方式不同,加载资源的方法如下

Reader getResoutceAsReader(String resource)

Stream getResourceAsStream(String resource)

File getResourceAsFile(String resource)

Properties getResourceAsProperties(String resource);

Url getResourceAsUrl(String resource)

继续各种操作吧

查询

通过主键ID查询

dao类

package com.sicheng.dao;

import com.sicheng.entity.User;

import java.util.List;

public interface UserMapper {

    //猛查
    List<User> selectUser();

    //通过ID查
    User selectUserById(int id);

//    //通过name、pwd查
//    List<User> selectUserByNameAndPwd(String name, String pwd);
//
//    //key模糊查询
//    List<User> selectUserByLikeKey(String key);
}

 

mapper文件

<?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.sicheng.dao.UserMapper">
    <select id="selectUser" resultType="com.sicheng.entity.User">
        select * from user;
    </select>

    <select id="selectUserById" resultType="com.sicheng.entity.User" parameterType="int">
        select * from user where id=#{id}
    </select>
</mapper> 

 

注意一下:

  • 当只有一个,参数的时候,就都可以不用写;
  • 接入,参数有两个,那写不写都会错的。

 

 

上面必错!!!!! 

Test文件

import com.sicheng.dao.UserMapper;
import com.sicheng.entity.User;
import com.sicheng.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class MybatisTest {

    @Test
    public void selectUser(){
        SqlSession session = MybatisUtils.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        List<User> users = userMapper.selectUser();
        for (User user :users) {
            System.out.println(user);
        }
    }

    @Test
    public void selectUserById(){
        SqlSession session = MybatisUtils.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        User user = userMapper.selectUserById(2);
        System.out.println(user);
    }
}

通过name属性查询

主要是想测试下,当parameterType是复杂类型的,即对象的时候,不写会不会报错

发现并没有什么问题!!!!

dao类

package com.sicheng.dao;

import com.sicheng.entity.User;

import java.util.List;

public interface UserMapper {

    //猛查
    List<User> selectUser();

    //通过ID查
    User selectUserById(int id);

    //通过name属性查
    List<User> selectUserByName(String name);
}

 

mapper配置文件

 

<?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.sicheng.dao.UserMapper">
    <select id="selectUser" resultType="com.sicheng.entity.User">
        select * from user;
    </select>

    <select id="selectUserById" resultType="com.sicheng.entity.User" parameterType="int">
        select * from user where id=#{id}
    </select>

    <select id="selectUserByName" resultType="com.sicheng.entity.User">
        select * from user where name = #{name};
    </select>
</mapper> 

 

 

 

test文件

 

import com.sicheng.dao.UserMapper;
import com.sicheng.entity.User;
import com.sicheng.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class MybatisTest {

    @Test
    public void selectUser(){
        SqlSession session = MybatisUtils.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        List<User> users = userMapper.selectUser();
        for (User user :users) {
            System.out.println(user);
        }
    }

    @Test
    public void selectUserById(){
        SqlSession session = MybatisUtils.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        User user = userMapper.selectUserById(2);
        System.out.println(user);
    }

    @Test
    public void selectUserByName(){
        SqlSession session = MybatisUtils.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        List<User> users = userMapper.selectUserByName("张三");
        for (User user :
                users) {
            System.out.println(user);
        }
    }
}

 

 

 

通过根据密码、名字查询

这下传入两种参数,怎么办呢?

第一种方法

@Param(“mapper文件需要调用的名字”)

dao类
package com.sicheng.dao;

import com.sicheng.entity.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface UserMapper {

    //猛查
    List<User> selectUser();

    //通过ID查
    User selectUserById(int id);

    //通过name属性查
    List<User> selectUserByName(String name);

    //通过name、pwd值进行查询
    List<User> selectUserByNameAndPwd(@Param("name") String name, @Param("pwd") String pwd);
}

 

mapper配置文件
<?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.sicheng.dao.UserMapper">
    <select id="selectUser" resultType="com.sicheng.entity.User">
        select * from user;
    </select>

    <select id="selectUserById" resultType="com.sicheng.entity.User" parameterType="int">
        select * from user where id=#{id}
    </select>

    <select id="selectUserByName" resultType="com.sicheng.entity.User">
        select * from user where name = #{name};
    </select>

    <select id="selectUserByNameAndPwd" resultType="com.sicheng.entity.User">
        select * from user where name = #{name} and pwd=#{pwd};
    </select>

</mapper> 

 

test文件
import com.sicheng.dao.UserMapper;
import com.sicheng.entity.User;
import com.sicheng.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class MybatisTest {

    @Test
    public void selectUser(){
        SqlSession session = MybatisUtils.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        List<User> users = userMapper.selectUser();
        for (User user :users) {
            System.out.println(user);
        }
    }

    @Test
    public void selectUserById(){
        SqlSession session = MybatisUtils.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        User user = userMapper.selectUserById(2);
        System.out.println(user);
    }

    @Test
    public void selectUserByName(){
        SqlSession session = MybatisUtils.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        List<User> users = userMapper.selectUserByName("张三");
        for (User user :
                users) {
            System.out.println(user);
        }
    }

    @Test
    public void selectUserByNameAndPwd(){
        SqlSession session = MybatisUtils.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        List<User> users = userMapper.selectUserByNameAndPwd("张三", "abcde");
        for (User user :
                users) {
            System.out.println(user);
        }
    }
}

 

第二种方法

使用Map进行传输

dao类
package com.sicheng.dao;

import com.sicheng.entity.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

public interface UserMapper {

    //猛查
    List<User> selectUser();

    //通过ID查
    User selectUserById(int id);

    //通过name属性查
    List<User> selectUserByName(String name);

    //通过name、pwd值进行查询
    List<User> selectUserByNameAndPwd(Map<String, String> map);
}

 

mapper配置文件
<?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.sicheng.dao.UserMapper">
    <select id="selectUser" resultType="com.sicheng.entity.User">
        select * from user;
    </select>

    <select id="selectUserById" resultType="com.sicheng.entity.User" parameterType="int">
        select * from user where id=#{id}
    </select>

    <select id="selectUserByName" resultType="com.sicheng.entity.User">
        select * from user where name = #{name};
    </select>

    <select id="selectUserByNameAndPwd" resultType="com.sicheng.entity.User" parameterType="map">
        select * from user where name = #{name} and pwd=#{pwd};
    </select>

</mapper> 

 

test文件
import com.sicheng.dao.UserMapper;
import com.sicheng.entity.User;
import com.sicheng.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MybatisTest {

    @Test
    public void selectUser(){
        SqlSession session = MybatisUtils.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        List<User> users = userMapper.selectUser();
        for (User user :users) {
            System.out.println(user);
        }
    }

    @Test
    public void selectUserById(){
        SqlSession session = MybatisUtils.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        User user = userMapper.selectUserById(2);
        System.out.println(user);
    }

    @Test
    public void selectUserByName(){
        SqlSession session = MybatisUtils.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        List<User> users = userMapper.selectUserByName("张三");
        for (User user :
                users) {
            System.out.println(user);
        }
    }

    @Test
    public void selectUserByNameAndPwd(){
        SqlSession session = MybatisUtils.getSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        Map<String, String> map = new HashMap<String, String>();
        map.put("name", "张三");
        map.put("pwd", "abcde");
        List<User> users = userMapper.selectUserByNameAndPwd(map);
        for (User user :
                users) {
            System.out.println(user);
        }
    }
}

 

模糊查询

dao类

package com.sicheng.dao;

import com.sicheng.entity.User;


import java.util.List;
import java.util.Map;

public interface UserMapper {

    //猛查
    List<User> selectUser();

    //通过ID查
    User selectUserById(int id);

    //通过name属性查
    List<User> selectUserByName(String name);

    //通过name、pwd值进行查询
    List<User> selectUserByNameAndPwd(Map<String, String> map);

    List<User> selectUserLikeName(String str);
    //插入
    int insertUser(User user);

    //更新
    int updateUser(User user);

    //删除
    int deleteUser(User user);
}

 

mapper配置文件

<?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.sicheng.dao.UserMapper">
    <select id="selectUser" resultType="com.sicheng.entity.User">
        select * from user;
    </select>

    <select id="selectUserById" resultType="com.sicheng.entity.User" parameterType="int">
        select * from user where id=#{id}
    </select>

    <select id="selectUserByName" resultType="com.sicheng.entity.User">
        select * from user where name = #{name};
    </select>

    <select id="selectUserByNameAndPwd" resultType="com.sicheng.entity.User" parameterType="map">
        select * from user where name = #{name} and pwd=#{pwd};
    </select>

    MyBatis-----1.MyBatis简介和使用

MyBatis学习笔记 —— MyBatis简介

MyBatis简介

Android 逆向类加载器 ClassLoader ( 类加载器源码简介 | BaseDexClassLoader | DexClassLoader | PathClassLoader )(代码片段

Mybatis入门

Mybatis入门