整合步骤

  • 导入必须jar包
    • mybatis核心jar包
    • mybatis依赖jar包
    • 数据库驱动包
  • 建立数据库表
  • 建立实体类
  • 建立Mapper接口
  • 建立sql映射文件
<?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">
<!-- 编写sql语句 -->
<mapper namespace="com.fei.dao.CustomerMapper">
    <select id="selectList" resultType="com.fei.domain.Customer">
        select * from t_customer
    </select>
</mapper>
  • 建立sqlMapConfig.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>
    <!-- 读取配置文件 -->
    <properties resource="db.properties" />

    <!-- 配置数据库连接池 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mapper/CustomerMapper.xml" />
    </mappers>
</configuration>
  • 编写测试类
// 0创建SqlSessionFactoryBuilder
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
// 1加载sqlMapConfig.xml配置文件
InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");

// 2创建sqlSessionFactory
SqlSessionFactory factory = builder.build(is);
// 3打开SqlSession
SqlSession sqlSession = factory.openSession();

// 4获取Mapper接口的对象
CustomerMapper customerMapper = sqlSession.getMapper(CustomerMapper.class);

// 5.操作
Customer customer = new Customer();
customer.setName("小明85");
customer.setPhone("18801069853");
customer.setGender("男");
customer.setAddress("北京市海淀区");

customerMapper.insert(customer);

// 6提交事务
sqlSession.commit();
// 7关闭连接
sqlSession.close();
01-18 02:59