Spring3+mybatis3泛型dao(或映射器)



我已经集成了spring3 + mybatis3,效果很好。

然后我发现很多sql会这样写:

select * from table1 where id=#{id}
select * from table2 where id=#{id}

我们不需要重复作为一个程序员!

那么,我们可以定义一个泛型的dao或映射器来避免这种重复吗?提供一个演示会更好。

一些链接也可以提供帮助。

这件事困扰了我很长时间,需要帮助。

我想这样写我的代码:

Test.java :

just a enity.

TestMapper.java :

public interface TestMapper extends GenericMapper {
    public void testMethod1(String..);
    //other methods here
}

GenericMapper.java :

public interface GenericMapper<T, PK> {
    public T select(PK id);
    public boolean update(T t);
    public boolean delete(PK id);
    public boolean insert(T t);
}

defind bean in spring-xx.xml:

<bean id="testMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    <property name="mapperInterface" value="com.jackson.mapper.TestMapper" />
</bean>

像这样调用我的服务层://请**注意**:方法select在GenericMapper中定义。

TestService.java :

public TestMapper testMapper;
public Test get(Integer id) {
    Test test = testMapper.select(id);   
    doSmth(test);
}

就在几分钟前,有人说我们可以使用拦截器接口。我现在正在努力。

谢谢!

杰克逊

,

其中一个选项是使用mybatis-generator

http://classnotfound.net/blog/mybatisspringgenerics/

我认为这个教程正是你正在寻找的。我不确定他运行的是哪个版本的Java(或编辑器配置),但我不得不添加Dao方法,并抑制未检查的类型转换(T)和原始类型警告,以使其在使用Java 8的eclipse mars 2上工作。

我知道我可能会迟到,但这个图书馆从谷歌将解决您的问题。我已经在10多个项目中使用它了

最新更新