天天看點

Mybatis 無Spring基本配置

1 基本配置

檢視官網

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>
  <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="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>
           

1.2 sql映射檔案 BlogMapper.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="org.mybatis.example.BlogMapper">
  <select id="selectBlog" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>
           

1.3 java 代碼查詢

/*  */
//1. 根據xml全局配置檔案,建立一個sqlSessionFactory對象(有資料源及一些運作環境資訊)
//2. sql映射檔案,配置了每一個sql,以及sql的封裝規則等
//3. 将sql映射檔案注冊在全局配置檔案中
//4. 使用全局配置檔案得到sqlSessionFactory
//5. 使用sqlSessionfactory工廠,擷取到sqlsession對象執行語句
//6. 一個sqlsession代表和資料庫的一次會話,用完關閉。sqlSession和connection一樣都是非線程安全的,每次使用應該擷取新的對象
//7. 使用唯一辨別告訴mybatis執行哪一條sql
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
		//參數1:唯一辨別
        //參數2:執行sql參數
        // select * from Blog where id = 126
  Blog blog = session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
} finally {
	session.close();
}
           
/* 使用接口方式 */
// 建立BlogMapper接口 接口内添加selectBlog方法
// BlogMapper.xml 中namespace設為BlogMapper接口的全類名,語句的id設為方法名
//擷取mapper代理BlogMapper接口實作,執行接口内的方法
try (SqlSession session = sqlSessionFactory.openSession()) {
  BlogMapper mapper = session.getMapper(BlogMapper.class);
  Blog blog = mapper.selectBlog(101);
} finally {
	session.close();
}
           

繼續閱讀