mybatisMybatis

mybatis-3.4.6 配置介绍

2020-07-19  本文已影响0人  晴天哥_王志

系列

开篇

mybatis配置

MyBatis 的配置文件,参考configuration。 配置文档的顶层结构如下:

configuration

<?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="dbConfig.properties">
        <property name="xx" value="yy"/>
    </properties>

    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/imooc-course?useUnicode=true"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mapper/imcUserMapper.xml"/>
    </mappers>

</configuration>

mapper

<?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="cn.edu.example.mapper.UserMapper">
    
    <select id="getById" parameterType="int" resultType="cn.edu.example.entity.ImcUser">
        SELECT user_nick AS userNick FROM imc_user WHERE user_id = #{userId};
    </select>

    <update id="updateSexById" parameterType="map">
        UPDATE imc_user SET sex = #{sex} WHERE user_id = #{userId};
    </update>
</mapper>

mybatis运行

public class MybatisHelloWorld {

    public static void main(String[] args) {

        String resouce = "configuration.xml";
        Reader reader;
        try {
            reader = Resources.getResourceAsReader(resouce);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

            SqlSession sqlSession = sqlSessionFactory.openSession();
            try {
                UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
                ImcUser imcUser = userMapper.getById(1);
                System.out.println(imcUser.getUserNick());
            } finally {
                sqlSession.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

参考文章

上一篇下一篇

猜你喜欢

热点阅读