思路:我們只需要寫 mapper 接口(相當(dāng)于 dao 接口),而不需要實(shí)現(xiàn)接口.在編寫 mapper.xml 映射文件.
開發(fā)規(guī)范
注:mybatis 可以自動(dòng)生成 mapper 接口的實(shí)現(xiàn)類代理對(duì)象.
第一步
在 mapper.xml 中 namespace 的值要為mapper 接口的包名+接口名.
<mapper namespace="cc.ibadboy.mybatis.mapper.UserMapper">
</mapper>
第二步
public interface UserMapper {
public String findById(int id);
}
mapper.java接口中的方法名要和 mapper.xml映射文件中的 id 值一樣.
<select id="findById" resultType="String" parameterType="int">
</select>
第三步
public interface UserMapper {
public String findById(int id);
}
mapper.java接口中的方法參數(shù)要和 mapper.xml映射文件中的 parameterType 值一樣.
<select id="findById" resultType="String" parameterType="int">
</select>
第四步
public interface UserMapper {
public String findById(int id);
}
mapper.java接口中的方法返回值類型要和 mapper.xml映射文件中的 resultType 值一樣.
<select id="findById" resultType="String" parameterType="int">
</select>
實(shí)現(xiàn)
//這幾個(gè)步驟是必須的,因?yàn)楸仨氁玫絊qlSessionFactory
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
//創(chuàng)建Mapper代理對(duì)象
UserMapper userMapper = session.getMapper(UserMapper.class);
//通過接口調(diào)用代理對(duì)象中的方法.
String userName = userMapper.findById(1);
System.out.println(userName);
session.close();
原理:其實(shí)代理對(duì)象內(nèi)部調(diào)用 selectOne 或 selectList
補(bǔ)充知識(shí)
別名
<typeAliases>
<package name=""></package>
<typeAlias type="" alias=""></typeAlias>
</typeAliases>
package:寫包路徑,別名就為包下的類名.
typeAlias:包路徑與類名,別名alias指定.
注:別名在使用的時(shí)候是不區(qū)分大小寫的.