mybatis獨立使用,注解sql

平時都是集成在框架里使用的,單元測試的時候需要從文件維護些數(shù)據(jù)到數(shù)據(jù)庫,就寫了下獨立使用的代碼

MybatisTest.java
package com.seer.mybatis;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class MybatisTest {
    @Test
    public void run() throws IOException {
        InputStream inputStream = new FileInputStream(new File("D:\\Code\\oilCard\\src\\test\\java\\com\\sdgs\\mob\\mybatis\\mybatis-config.xml"));

        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        Mapper mapper = sqlSession.getMapper(Mapper.class);

        int count = mapper.test();
        System.out.println(count);
    }
}

mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="cacheEnabled" value="false"/>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="true"/>
        <!-- 打印查詢語句 -->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!-- 使用jdbc的getGeneratedKeys獲取數(shù)據(jù)庫自增主鍵值 -->
        <!-- <setting name="useGeneratedKeys" value="true" /> -->
        <!-- 使用列別名替換列名 默認:true -->
        <!-- <setting name="useColumnLabel" value="true" /> -->
        <!-- 開啟駝峰命名轉(zhuǎn)換:Table{create_time} -> Entity{createTime} -->
        <!-- <setting name="mapUnderscoreToCamelCase" value="true" /> -->
    </settings>

    <environments default="test">
        <environment id="test">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="username" value="用戶名"/>
                <property name="password" value="密碼"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true"/>
                <property name="driver" value="com.mysql.jdbc.Driver"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!-- 加載mapper文件,直接加載class -->
        <mapper class="com.seer.mybatis.Mapper"/>
    </mappers>
</configuration>

Mapper.java
package com.seer.mybatis;

import org.apache.ibatis.annotations.Select;

interface Mapper {
    // 注解sql,復(fù)雜的實現(xiàn)百度下
    @Select("select count(1) from sys_province")
    int test();
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容