1. 程式人生 > >後端-框架-Spring-MyBatis

後端-框架-Spring-MyBatis

後端-框架-Spring-MyBatis-整合

基礎類(基礎)

public class UserMapperImpl implements UserMapper { 
	private SqlSessionTemplate sqlSession;
    public SqlSessionTemplate getSqlSession() {
    	return sqlSession;
    }
	public void setSqlSession(SqlSessionTemplate sqlSession) {
		this.sqlSession = sqlSession;
} public List<User> getUserList(User user) { return sqlSession.selectList("cn.smbms.dao.user.UserMapper.getUserList", user); } }

其中的配置檔案

	<bean id="DataSource" class="org.apache.commons.dbcp2.BasicDataSource">
		<!-- 其中&符號用&amp;代替 -->
		<property name="driverClassName"
value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=true"/> <property name="username" value="root" /> <property name="password" value="1234" /> </bean> <bean id="SqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 可以根據類按F3,F4檢視其中屬性方法 --> <property name="dataSource" ref="DataSource"></property> <property name="configLocation" value="classpath:myBatis-config.xml"></property> <property name="mapperLocations"> <list> <value>classpath:cn/smbms/dao/UserMapper.xml</value> </list> </property> </bean> <bean id="SqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="SqlSessionFactory" ref="SqlSessionFactory"></constructor-arg> </bean> <bean id="UserMapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSession" ref="SqlSessionTemplate"></property> </bean>

基礎類(偷懶)

//SqlSessionDaoSupport支援不用自己建SqlSessionTemplate
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper { 
	public List<User> getUserList(User user) {
		return this.getsqlSession().selectList("cn.smbms.dao.user.UserMapper.getUserList", user);
    }
}

其中的配置檔案(偷懶)

	<bean id="DataSource" class="org.apache.commons.dbcp2.BasicDataSource">
		<!-- 其中&符號用&amp;代替 -->
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=true"/>
		<property name="username" value="root" />
		<property name="password" value="1234" />
	</bean>
	
	<bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	<!-- 可以根據類按F3,F4檢視其中屬性方法 -->
		<property name="dataSource" ref="DataSource"></property>
		<property name="configLocation" value="classpath:myBatis-config.xml"></property>
		<property name="mapperLocations">
			<list>
				<value>classpath:cn/smbms/dao/UserMapper.xml</value>
			</list>
		</property>
	</bean>
	
	<bean id="UserMapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    	<property name="sqlSessionFactory" ref="SqlSessionFactory"></property>
    </bean>
所使用的包
package Value
mybatis-spring.jar
commons-dbcp.jar
commons-logging.jar
commons-pool.jar