MyBatis入门案例

一.使用Maven添加依赖

<dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatisartifactId>
        <version>3.4.6version>
    dependency>
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>5.1.32version>
    dependency>

二.创建实体类

MyBatis入门案例_第1张图片

三.创建dao层的UserDao接口

MyBatis入门案例_第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">

```xml
<configuration >
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="001011"/>
            </dataSource>
        </environment>
    </environments>
<mappers>
    <mapper resource="top/kui/dao/UserDaoMapper.xml"/>
</mappers>
</configuration>

五.创建UserMapper配置文件

注意:此配置文件要跟UserDao接口所在包层次结构一样
UserDao接口

MyBatis入门案例_第3张图片

创建xml文件使要使用xx/xxx/xxx而不是 xxx.xxx.xx


```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="top.kui.dao.UserDao">
    <select id="findAll" resultType="top.kui.domain.User" >
        select * from user;
    </select>
</mapper>

六.编写测试类

在main方法中运行

public static void main(String[] args) throws IOException {
        InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

        SqlSessionFactory sessionFactory = builder.build(in);
        SqlSession sqlSession = sessionFactory.openSession();

        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<User> all = mapper.findAll();
        for (User user : all) {
            System.out.println(user);
        }
        sqlSession.close();
        in.close();

    }

你可能感兴趣的:(maven,java,intellij-idea)