因最近會用到mybatis相關,好久木有用了, 趕緊來回顧以及記錄并分享下:
這一章先來分享一下單表查詢是如何實作的:
一、添加mybatis依賴
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>x.x.x</version>
</dependency>
二、添加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>
<!-- 配置實體類對應xml檔案-->
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
三、讀取xml檔案建立SqlSessionFactory對象
//配置檔案路徑
String resource = "org/mybatis/example/mybatis-config.xml";
//擷取配置檔案
InputStream inputStream = Resources.getResourceAsStream(resource);
//通過配置檔案擷取SqlSessionFactory對象
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
四、建立sql語句以及建立SqlSession對象
1)配置sql查詢語句
<?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">
<!-- 以id為參數查詢結果-->
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>
2)建立SqlSession對象
try (SqlSession session = sqlSessionFactory.openSession()) {
Blog blog = session.selectOne(
"org.mybatis.example.BlogMapper.selectBlog", 101);
}