阅读 32

Mybatis基础使用

1.添加项目需要的依赖

<dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.6</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.46</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
    </dependency>
复制代码

2.在resoueces中添加mybatis主配置文件mybatis.xml

在主配置文件中添加数据库信息及具体mapper映射 此处省略创建数据库及子表和添加数据

  <?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/mytest"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/usersMapper.xml"/>
    </mappers>
</configuration>
复制代码

3.创建数据库表对应的实体类Users

保持实体类和表中的字段名一致

4.创建Users的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.zhangflg.mybatis.entity.Users">
    <select id="usersList" resultType="com.zhangflg.mybatis.entity.Users">
        select * from users
    </select>
</mapper>
复制代码

5.测试mybatis基础使用

String resources = "mybatis.xml";

        InputStream is = Resources.getResourceAsStream(resources);

        SqlSessionFactory factory =
                new SqlSessionFactoryBuilder().build(is);

        SqlSession session = factory.openSession();
        List<Users> ulist = session.selectList("usersList");
        for (Users u : ulist) {
            System.out.println(u);
        }
        session.close();
复制代码