设为首页 - 加入收藏
您的当前位置:主页 > 资源 > 技术文章 > 正文

spring+mybatis把Dao接口当成Mapper代理使用

来源:未知 编辑:admin 时间:2017-09-16
核心思想:
就是将Mapper接口类直接转成Dao使用。
Configuration sample:
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="org.mybatis.spring.sample.mapper" />
<!-- optional unless there are multiple session factories defined -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
上面的类配置的配本质就是使用:MapperFactoryBean的过程:
org.mybatis.spring.mapper.MapperFactoryBean<T>
BeanFactory that enables injection of MyBatis mapper interfaces. It can be set up with a SqlSessionFactory or a pre-configured SqlSessionTemplate.
Sample configuration:
<bean id="baseMapper" class="org.mybatis.spring.mapper.MapperFactoryBean" abstract="true" lazy-init="true">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<bean id="oneMapper" parent="baseMapper">
<property name="mapperInterface" value="my.package.MyMapperInterface" />
</bean>
<bean id="anotherMapper" parent="baseMapper">
<property name="mapperInterface" value="my.package.MyAnotherMapperInterface" />
</bean>
Note that this factory can only inject interfaces, not concrete classes.
示例:
现在只需要开发一个接口,并在接口中声明在mapper.xml中开发的方法:
package cn.ssm.dao;
import cn.ssm.domain.User;
public interface UserDao {
public int insert(User u);
}
开发mapper.xml文件:
<?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="cn.ssm.dao.UserDao">
<insert id="insert" parameterType="cn.ssm.domain.User">
insert into users values(#{id},#{name},'22')
</insert>
</mapper>
现在UserDao会被解析成:userDao的spring id。类似于:
<bean id="baseMapper" class="org.mybatis.spring.mapper.MapperFactoryBean" abstract="true" lazy-init="true">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<bean id="userDao" parent="baseMapper">
<property name="mapperInterface" value="cn.ssm.dao.UserDao" />
</bean>
只能是接口,不能是具体类。
现在就可以在Service中引用了:
package cn.ssm.service;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import cn.ssm.dao.UserDao;
import cn.ssm.domain.User;
@Service("userService")
public class UserServiceImpl {
@Resource(name="userDao")
private UserDao dao;
public void save() {
System.err.println("dao :"+dao+","+dao.getClass());
User uu = new User();
uu.setId("YYY001100");
uu.setName("TTTTT100");
dao.insert(uu);
}
}

相关文章:

相关推荐:

网友评论:

发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片

有乐趣咨询 www.peixinhotelbeijing.cn 联系QQ:4988723 邮箱:4988723@qq.com

Copyright © 2002-2017 DEDECMS. 东吴科技 版权所有 Power by DongWU

Top