美文网首页
Mybatis 源码阅读(一)搭建项目

Mybatis 源码阅读(一)搭建项目

作者: 竹本辰 | 来源:发表于2018-10-28 15:51 被阅读0次

    最好的教程还是官方文档,所以这里先贴上来。
    http://www.mybatis.org/mybatis-3/zh/getting-started.html

    搭建一个MyBatis项目

    这里先搭建一个项目,方便后面阅读源码。
    这里接下一篇文章《MyBatis源码(二)创建SqlSessionFactory》
    https://www.jianshu.com/p/eb3d06a7c77d

    创建一个实体类

    getter、setter、toString方法自动生成即可。

    public class Country {
        private Long id;
        private String countryName;
        private String countryCode;
    
        ...
    }
    

    创建持久化接口

    import com.xingchen.mybatis.entity.Country;
    import java.util.List;
    
    public interface CountryMapper {
        List<Country> selectAll();
    }
    

    创建CountryMapper.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.xingchen.mybatis.mapper.CountryMapper">
        <resultMap id="countryMap" type="Country">
            <result property="id" column="id"/>
            <result property="countryName" column="country_name"/>
            <result property="countryCode" column="country_code"/>
        </resultMap>
    
        <select id="selectAll" resultMap="countryMap">
          select * from country
        </select>
    </mapper>
    

    创建数据库并录入数据

        SET NAMES utf8mb4;
        SET FOREIGN_KEY_CHECKS = 0;
        
        -- ----------------------------
        -- Table structure for country
        -- ----------------------------
        DROP TABLE IF EXISTS `country`;
        CREATE TABLE `country` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `country_name` varchar(255) DEFAULT NULL,
          `country_code` varchar(255) DEFAULT NULL,
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
        
        -- ----------------------------
        -- Records of country
        -- ----------------------------
        BEGIN;
        INSERT INTO `country` VALUES (1, '中国', 'CN');
        INSERT INTO `country` VALUES (2, '美国', 'US');
        INSERT INTO `country` VALUES (3, '俄罗斯', 'RU');
        INSERT INTO `country` VALUES (4, '英国', 'GB');
        INSERT INTO `country` VALUES (5, '法国', 'FR');
        COMMIT;
        
        SET FOREIGN_KEY_CHECKS = 1;
    

    创建数据库配置文件

    创建的数据库就命名为mybatis

    下面的sql语句是新建country表,并录入数据。
    创建文件db.properties,用来保存数据库连接信息。

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/mybatis?useSSL=false
    username=root
    password=root
    

    创建MyBatis配置文件

    这部分基本上参考官方文档即可。

    创建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>
        <!-- 这个配置文件中存储了数据库连接的相关信息 -->
        <properties resource="mybatis/db.properties"></properties>
    
        <typeAliases>
            <package name="com.xingchen.mybatis.entity"/>
        </typeAliases>
    
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="${driver}"/>
                    <property name="url" value="${url}"/>
                    <property name="username" value="${username}"/>
                    <property name="password" value="${password}"/>
                </dataSource>
            </environment>
        </environments>
        <mappers>
            <mapper resource="mybatis/mapper/CountryMapper.xml"/>
        </mappers>
    </configuration>
    

    创建测试类

    import com.xingchen.mybatis.entity.Country;
    import com.xingchen.mybatis.mapper.CountryMapper;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    import java.io.Reader;
    import java.util.List;
    
    /**
     * @author chen
     * @Date 2018/10/24
     * mybatis 源码阅读
     * */
    public class MyTest {
        private static SqlSessionFactory sqlSessionFactory=null;
    
        static {
            try{
                Reader reader= Resources.getResourceAsReader("mybatis/mybatis-config.xml");
                sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
                reader.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    
        public static void main(String[] args) {
            SqlSession sqlSession=sqlSessionFactory.openSession();
            try {
                CountryMapper countryMapper=sqlSession.getMapper(CountryMapper.class);
                List<Country> countries=countryMapper.selectAll();
                for(Country country:countries){
                    System.out.println(country);
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                sqlSession.close();
            }
        }
    }
    

    ​​运行结果

    Country{id=1, countryName='中国', countryCode='CN'}
    Country{id=2, countryName='美国', countryCode='US'}
    Country{id=3, countryName='俄罗斯', countryCode='RU'}
    Country{id=4, countryName='英国', countryCode='GB'}
    Country{id=5, countryName='法国', countryCode='FR'}
    

    相关文章

      网友评论

          本文标题:Mybatis 源码阅读(一)搭建项目

          本文链接:https://www.haomeiwen.com/subject/igrdtqtx.html