dao实现类UserDaoImpl2,,代码如下:
Java代码
public class UserDaoImpl2 implements UserDao {
private UserMapper userMapper;
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
public User getUserById(User user) {
return userMapper.getUser(user.getId());
}
}
2、采用接口org.apache.ibatis.session.SqlSession的实现类org.mybatis.spring.SqlSessionTemplate。
mybatis中, sessionFactory可由SqlSessionFactoryBuilder.来创建。
MyBatis-Spring 中,使用了SqlSessionFactoryBean来替代。
SqlSessionFactoryBean有一个必须属性dataSource,
另外其还有一个通用属性configLocation(用来指定mybatis的xml配置文件路径)。
(1)Spring配置文件:
<!-- 创建SqlSessionFactory,同时指定数据源-->
<bean id="sqlSessionFactory" class="org.mybatis./>
<!--指定实体类映射文件,可以指定同时指定某一包以及子包下面的所有配置文件,mapperLocations和configLocation有一个即可,当需要为实体类指定别名时,可指定configLocation属性,再在mybatis总配置文件中采用mapper引入实体类映射文件 -->
<!- - <property name="mapperLocations" value="classpath*:com/xxt/ibatis/dbcp/**/*.xml"/> -->
<bean>
(2)mybatis总配置文件sqlMapConfig.xml:
<configuration>
<typeAliases>
<typeAlias type="com.xxt.ibatis.dbcp.domain.User" alias="User" />
</typeAliases>
<mappers>
<mapper resource="com/xxt/ibatis/dbcp/domain/user.map.xml" />
</mappers>
</configuration>
(3)实体类映射文件user.map.xml:
<mapper namespace="com.xxt.ibatis.dbcp.domain.User">
<resultMap type="User" id="userMap">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="password" column="password" />
<result property="createTime" column="createtime" />
</resultMap>
<select id="getUser" parameterType="User" resultMap="userMap">
select * from user where id = #{id}
</select>
<mapper/>
(4)dao层接口实现类UserDaoImpl:
Java代码
public class UserDaoImpl implements UserDao {
public SqlSessionTemplate sqlSession;
public User getUserById(User user) {
return (User)sqlSession.selectOne("com.xxt.ibatis.dbcp.domain.User.getUser", user);
}
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession; }
}
3、采用抽象类org.mybatis.
spring.support.SqlSessionDaoSupport提供SqlSession。
(1)
spring配置文件:
Java代码
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:sqlMapConfig.xml"/>
<!-- <property name="mapperLocations" value="classpath*:com/xxt/ibatis/dbcp/domain/user.map.xml"/ > -->
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<bean id="userDaoImpl3" class="com.xxt.ibatis.dbcp.dao.impl.UserDaoImpl3">
<!--注入SqlSessionTemplate实例 -->
<property name="sqlSessionTemplate" ref="sqlSession" />
<!--也可直接注入SqlSessionFactory实例,二者都指定时,SqlSessionFactory失效 -->
<!-- <property name="sqlSessionFactory" ref="sqlSessionFactory" /> -->
</bean>
(2) dao层接口实现类UserDaoImpl3:
Java代码
public class UserDaoImpl3 extends SqlSessionDaoSupport implements UserDao {
public User getUserById(User user) {
return (User) getSqlSession().selectOne("com.xxt.ibatis.dbcp.domain.User.getUser", user);
}
}