【Mybatis】入门程序

一、需求:根据用户id查询用户信息

二、环境

java环境:JDK1.7.0
mysql:5.6.24
mybatis运行环境(jar包):3.2.7
加入mysql驱动包,免费下载:mysql-connector-java-5.1.7-bin.jar

三、log4j.properties

# Global logging configuration
# 在开发环境下日志级别设置成DEBUG,生产环境设置成info或error
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

四、工程结构

【Mybatis】入门程序_第1张图片

五、SqlMapConfig.xml编写



<configuration>

    
    <properties resource="db.properties">
        
        
    properties>
    
    <typeAliases>

        
        
        
        <package name="cn.itcast.mybatis.po"/>

    typeAliases>

    
    <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>

configuration>

六、查询用户

1、创建po类
【Mybatis】入门程序_第2张图片

2、映射文件User.xml

<select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.User">
    SELECT * FROM USER WHERE id=#{value}
select>

3、SqlMapConfig.xml中加载User.xml

<mappers>
    <mapper resource="sqlmap/User.xml"/>
mappers>

4、程序编写

    private SqlSessionFactory sqlSessionFactory;

    // 此方法是在执行testFindUserById之前执行
    @Before
    public void setUp() throws Exception {
        // 创建sqlSessionFactory

        // mybatis配置文件
        String resource = "SqlMapConfig.xml";
        // 得到配置文件流
        InputStream inputStream = Resources.getResourceAsStream(resource);

        // 创建会话工厂,传入mybatis的配置文件信息
        sqlSessionFactory = new SqlSessionFactoryBuilder()
                .build(inputStream);
    }
    @Test
    public void testFindUserById() throws Exception {

        SqlSession sqlSession = sqlSessionFactory.openSession();

        //创建UserMapper对象,mybatis自动生成mapper代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        //调用userMapper的方法

        User user = userMapper.findUserById(1);

        System.out.println(user);

    }

总结
实践,加深理解。

你可能感兴趣的:(【架构设计】)