首先需要一個實體model User,並生成了所有成員變量的get、set方法及toString方法。
package self.exercise.bean; public class User { private String account; private int id; private String password; private String user_name; public User() { } public User(String account, String password, String user_name) { super(); this.account = account; this.password = password; this.user_name = user_name; } }
數據庫中的web表中的字段與User類中的變量一 一對應。
MyBatis實現對數據庫數據的操作有兩種方式,根據namespace+id的比較傳統的方式,以及根據可以合理描述參數和返回值的接口進行代理。
一、傳統方式
在映射文件中插入
<mapper namespace="self.exercise.dao"> <select id="load" resultType="self.exercise.bean.User"> select * from user where id = 1; </select> </mapper>
請保證namespace的值是唯一的。resultType中指定了User類所在的包。
在核心配置文件中的mappers標簽中插入,將映射文件與核心配置文件建立聯系。
<mapper resource="self/exercise/mapper/UserMapper.xml" />
從 XML 中構建 SqlSessionFactory
每個基於 MyBatis 的應用都是以一個 SqlSessionFactory 的實例為中心的。SqlSessionFactory 的實例可以通過 SqlSessionFactoryBuilder 獲得。而 SqlSessionFactoryBuilder 則可以從 XML 配置文件或一個預先定制的 Configuration 的實例構建出 SqlSessionFactory 的實例。
從 XML 文件中構建 SqlSessionFactory 的實例非常簡單,建議使用類路徑下的資源文件進行配置。但是也可以使用任意的輸入流(InputStream)實例,包括字符串形式的文件路徑或者 file:// 的 URL 形式的文件路徑來配置。MyBatis 包含一個名叫 Resources 的工具類,它包含一些實用方法,可使從 classpath 或其他位置加載資源文件更加容易。
String resource = "org/mybatis/example/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
從 SqlSessionFactory 中獲取 SqlSession
既然有了 SqlSessionFactory ,我們就可以從中獲得 SqlSession 的實例了。SqlSession 完全包含了面向數據庫執行 SQL 命令所需的所有方法。你可以通過 SqlSession 實例來直接執行已映射的 SQL 語句。例如:
sqlSession = sqlSessionFactory.openSession();
try{
User user = sqlSession.selectOne("self.exercise.dao.load");
}finally{
sqlSession.close();
}
二、接口代理
新建一個代理接口UserDao
package self.exercise.dao; import self.exercise.bean.User; public interface UserDao { User load(); }
此時,映射文件中的namespace必須是接口的路徑,即self.exercise.dao.UserDao
在測試代碼中將namespace+id方式替換為
sqlSession = sqlSessionFactory.openSession(); try{ User user = sqlSession.getMapper(UserDao.class).load(); }finally{ sqlSession.close(); }
另外,定制化SQL語句也可在接口中用注解方式實現,替代XML中select標簽的內容,例如:
package self.exercise.dao; import org.apache.ibatis.annotations.Select; import self.exercise.bean.User; public interface UserDao { @Select("select * from user where id = 1;") User load(); }
注解方式還是XML方式,傳統方式還是接口代理;可靈活搭配使用。