Mybatis結(jié)合Spring需要mybatis-spring.jar
備注:
DataSource由spring管理的,這里不闡述,spring的配置這里也不闡述,主要記錄MyBatis是怎么整合進(jìn)spring
1:添加MyBatisConfiguration.xml文件
[html] view plaincopy
<?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>
<typeAliases>
<typeAlias alias="App" type="com.pojo.App" />
</typeAliases>
<mappers>
<mapper resource="com/sqlmap/AppMapper.xml"/>
</mappers>
</configuration>
注釋:AppMapper.xml是mybatis查詢數(shù)據(jù)庫(kù)是所調(diào)用的映射文件
typeAliases是類型別名,使用它們你可以不用輸入類的全路徑,在映射文件中使用的,例如該例子中的app指的是java中的pojo,里面有appId和appName兩個(gè)字段
2:編寫映射文件
[html] view plaincopy
<?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="com.dao.AppMybatisDao">
<select id="selectApp" parameterType="App" resultType="App">
select app_name as appName from app where app_id=#{appId}
</select>
</mapper>
注釋:這里使用了mybatis的注解,App是一個(gè)pojo,我們使用他來(lái)傳值和賦值
3:編寫AppMybatisDao,只有一個(gè)方法如下:
[java] view plaincopy
public interface AppMybatisDao {
public App selectApp(App app);
}
4:編寫spring的配置文件
[html] view plaincopy
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="/WEB-INF/_conf/_myBatis/MyBatisConfiguration.xml"></property>
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="appMybatisDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.dao.AppMybatisDao"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
注釋:其實(shí)這里你可以把AppMapper.xml看做是AppMybatisDao的實(shí)現(xiàn)類;
你在其他地方引入appMybatisDao,調(diào)用其selectApp的方法,就會(huì)看到結(jié)果。
字符集問(wèn)題
若工程中配置文件的編碼(即encoding屬性)是UTF-8,再往這些文件添加中文注釋,則會(huì)報(bào)出類似“Invalid byte 1 of 1-byte UTF-8 sequence”的錯(cuò)誤。如下圖所示:
把編碼改為utf8或gbk即可解決此問(wèn)題。