在之前的文章中已經提及開發dao的方式,當初是單純的mybatis開發,分爲原始開發方式和基於mapper代理的方式,與Spring整合之後的開發同樣是這兩種方式,原始的開發方式需要程序員書寫dao接口和實現類,而且會存在很多問題,比如【005】提到的。
本章主要介紹使用mapper代理進行dao的開發。
【1】早在mapper文件下新建UserMapper.java接口文件。關鍵代碼:
public interface UserMapper {
//根據id查詢用戶信息
User findUserById(int id) throws Exception;
}
【2】修改配置文件resources\applicationContext.xml,加入如下代碼:
<!--原始dao接口--> <!--<bean id="userDao" class="dao.UserDaoImpl">--> <!--<property name="sqlSessionFactory" ref="sqlSessionFactory"/>--> <!--</bean>--> <!--配置mapper--> <!--<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">--> <!--<property name="mapperInterface" value="mapper.UserMapper"/>--> <!--<property name="sqlSessionFactory" ref="sqlSessionFactory"/>--> <!--</bean>--> <!--通過mapperScannerConfigure進行mapper掃描--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean>
【3】修改映射文件resources\sqlMap\User.xml
<mapper namespace="test"> <!-- 在 映射文件中配置很多sql語句 --> <!-- 需求:通過id查詢用戶表的記錄 --> <!-- 通過 select執行數據庫查詢 id:標識 映射文件中的 sql 將sql語句封裝到mappedStatement對象中,所以將id稱爲statement的id parameterType:指定輸入 參數的類型,這裏指定int型 #{}表示一個佔位符號 #{id}:其中的id表示 接收輸入 的參數,參數名稱就是id,如果輸入參數是簡單類型,#{}中的參數名可以任意,可以value或其它名稱 resultType:指定sql輸出結果 的所映射的java對象類型,select指定resultType表示將單條記錄映射成的java對象。--> <select id="findUserById" parameterType="int" resultType="po.User"> SELECT *FROM USER WHERE id=#{value} </select> </mapper>
【4】測試程序
public class UserMapperTest {
private ApplicationContext applicationContext;
//在setUp這個方法得到spring容器
@Before
public void setUp() throws Exception {
applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
}
@Test
public void testFindUserById() throws Exception {
UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");
User user = userMapper.findUserById(1);
System.out.println(user);
}
}
【5】結果如下: