MyBatis:HelloWorld入门

一、简介

1、什么是MyBatis

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。

2、官网地址

https://mybatis.org/mybatis-3/zh/index.html

3、依赖

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.6</version>
</dependency>

二、项目初体验

1、创建一个maven项目

2、添加依赖

点击查看代码
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</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>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
    </dependencies>

3、创建mybatis-config.xml配置文件

<?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/test"/>
                <property name="username" value="root"/>
                <property name="password" value="123"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/kw/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

4、创建mybatisUtils工具类

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

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

5、创建mapper接口,mapper.xml配置文件

mapper接口:

public interface EmployeeMapper {
    List<Employee> getEmployeeList();

    Employee getEmployeeById(int id);

    int addEmployee(Employee employee);

    int deleteEmployee(int id);

    int updateEmployee(Employee employee);
}

mapper.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="com.kw.mapper.EmployeeMapper">
    <select id="getEmployeeList" resultType="com.kw.pojo.Employee">
        select * from Employee
    </select>

    <select id="getEmployeeById" parameterType="int" resultType="com.kw.pojo.Employee">
        select * from Employee where id=#{id}
    </select>

    <insert id="addEmployee" parameterType="com.kw.pojo.Employee">
        insert into Employee(empName,empSex,empPhone,hireDate) values (#{empName},#{empSex},#{empPhone},#{hireDate})
    </insert>

    <delete id="deleteEmployee" parameterType="int">
        delete from Employee where id=#{id}
    </delete>

    <update id="updateEmployee" parameterType="com.kw.pojo.Employee">
        update Employee set empName=#{empName},empSex=#{empSex},empPhone=#{empPhone},hireDate=#{hireDate} where id=#{id}
    </update>
</mapper>

6、单元测试

传统方式:不需要接口文件,只需要编写xml配置文件即可。
List list=sqlSession.selectList("com.kw.mvc.mapper.UserMapper.getUserList");
接口方式:需要编写接口文件和xml配置文件,两者通过xml配置文件中的namespace属性进行关联。
UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
List list=userMapper.getUserList();

    @Test
    public void test(){
        SqlSession sqlSession =MybatisUtils.getSqlSession();
        /*List<User> list=sqlSession.selectList("com.kw.mvc.mapper.UserMapper.getUserList");*/
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        List<User> list=userMapper.getUserList();
        for (User user : list) {
            System.out.println(user);
        } 
        sqlSession.close();
    }

注意:maven项目构建时无法获取java或者resources文件夹下的xml等配置文件,需要在pom.xml文件添加构建

    <build>
        <resources>
            <resource>
                 <directory>src/main/java</directory>
                 <includes>
                     <include>**/*.xml</include>
                     <include>**/*.properties</include>
                 </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
posted @ 2021-12-14 15:55  amo丶k  阅读(35)  评论(0编辑  收藏  举报