MyBatis 学习总结(二)

1.MyBatis基础环境的搭建
1.1 核心配置文件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> 
    <typeAliases> 
        <typeAlias alias="User" type="com.mipo.entity.User"/> 
    </typeAliases> 
    <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?characterEncoding=utf-8"/> 
                <property name="username" value="root"/> 
                <property name="password" value="root"/> 
            </dataSource> 
        </environment> 
    </environments> 
    <mappers> 
        <mapper resource="com/mipo/mapping/UserMapper.xml"/> 
    </mappers>
</configuration>                    

1.2 配置映射文件UserMapper.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.mipo.mapping.UserMapper"> 
    <select id="selectUser" parameterType="Integer" resultType="User"> 
        SELECT * FROM T_USER WHERE ID = #{ID} 
    </select> 
</mapper>
    

1.3 编写junit单元测试

@Test
public void myBatisTest(){
    try {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new qlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = (User)sqlSession.selectOne("com.mipo.mapping.UserMapper.selectUser", Integer.valueOf(1));
        System.out.println(user);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

 

posted @ 2016-11-18 15:57  Qingdong.Li  Views(186)  Comments(0Edit  收藏  举报