MyBatis可以透過在xml中撰寫SQL,並將xml綁定到一個給程式呼叫的interface,如此程式就可以透過呼叫interface的方法來執行xml中對應的SQL,而綁定xml和interface的設定是在mapper(xml)檔的<mapper namespace>
。
<mapper namespace="idv.matt.dao.mapper.UserMapper">
例如有個給程式呼叫的interface UserMapper.java
如下,對應到UserMapper.xml
。
package idv.matt.dao.mapper;
public interface UserMapper {
User selectUser(String id);
}
綁定的UserMapper.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="idv.matt.dao.mapper.UserMapper">
<select id="selectUser" parameterType="String" resultType="hashmap">
SELECT USER_ID, USER_NAME, USER_AGE, USER_EMAIL
FROM USER_PROFILE
WHERE USER_ID = #{id}
</select>
</mapper>
所以在程式中要取得使用者資料,可以使用下面來呼叫。
String resource = "resources/mybatis-config.xml"; // mybatis配置檔的路徑
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream); // 取得SessionFactory
SqlSession session = sqlSessionFactory.openSession(); // 開啟一個Session
try {
UserMapper mapper = session.getMapper(UserMapper.class); // 取得Mapper實例
User user = mapper.selectUser("A001");
} finally {
session.close();
}
沒有留言:
張貼留言