【Mybatis】环境搭建和简单的CRUD

2.1 搭建环境

搭建数据库

新建一个普通maven项目mybatis

导入meven依赖

<!--导入依赖-->
<dependencies>
    <!--mysql驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.46</version>
    </dependency>
    <!--mybatis-->
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>
    <!--junit-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>

2.2 创建一个模块

  • 编写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="development">
        <environment id="development">
            <transactionManager type="JDBC"/>  <!--事务管理-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" 
                          value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
</configuration>
  • 编写mybatis的工具类
//SqlSessionFactory -- sqlSession
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            //使用mybatis的工具类第一步:获取sqlsessionfactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch (IOException e){
        }
    }
//   既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
//   SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
    public static SqlSession getSqlSession(){
     return sqlSessionFactory.openSession();
    }
}

2.3 编写代码

  • 实体类

    public class User {
        private String id;
        private String name;
        private String pwd;
    }
    
  • Dao接口

    public interface UserDao {
        List<User> getUserList();
    }
    
  • 接口实现类由原来的UserDaoImpl—>Mapper配置文件

    <!--绑定一个对应的Dao/Mapper接口-->
    <mapper namespace="com.dao.UserDao">
        <!--查询语句
        id:原本要在DaoImpl中实现的方法
        resultType:获取的结果
        -->
        <select id="getUserList" resultType="com.bean.User">
            select * from user;
        </select>
    </mapper>
    

    2.4 测试

  • Test 推荐使用第一种方法

    @Test
    public void test(){
        //获得sqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //方法一:getMapper
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.getUserList();
        //方法二:
        //List<User> userList = sqlSession.selectList("com.dao.UserDao.getUserList");
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }
    

注意:ErrorType interface com.dao.UserDao is not known to the MapperRegistry.

MapperRegistry是什么:Mapper需要在mybatis-conifg.xml中进行注册

Meven中将某个包下的xml文件当作约定文件的方法—父目录中 pom.xml:

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

可能会遇到的问题:

1.配置文件没有注册:Error**:**Type interface com.dao.UserDao is not known to the MapperRegistry.

2.绑定接口错误

3.方法名不对

4.返回类型不对

5.Meven导出资源问题

3、CRUD(增删改查)

3.1 namespace

namespace中的包名要和接口包名一致

3.2 select

选择,查询语句:

  • id:就是对应namespace中的方法名
  • resultType:就是sql语句执行的返回值
  • parameterType:参数类型
<select id="getUserById" parameterType="int" resultType="com.bean.User">
    select * from user where id =#{id}
</select>
@Test
public void test2(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    User user = userMapper.getUserById(1);
    System.out.println(user);
    sqlSession.close();
}

3.3 Insert

增删改需要提交事务

<!--对象中的属性,可以直接取出来-->
<insert id="addUser" parameterType="com.bean.User" >
    insert into user values (#{id},#{name},#{pwd});
</insert>
@Test
public void test3(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    userMapper.addUser(new User(4,"小美","112233"));
    sqlSession.commit();
    sqlSession.close();
}

3.4 update

<update id="editUser" parameterType="com.bean.User" >
    update user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
@Test
public void test4(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    userMapper.editUser(new User(2,"bb","123412"));
    sqlSession.commit();
    sqlSession.close();
}

3.5 delete

<delete id="deleteUser" parameterType="int">
    delete from user where id=#{id}
</delete>
@Test
public void test5(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    userMapper.deleteUser(4);
    sqlSession.commit();
    sqlSession.close();
}
上一篇:2019年深度学习Top 5研究论文,一文Get硬核干货:XLNet、网络剪枝、StarGAN


下一篇:在idea环境下构建springCloud