2

I have integrated spring3 + mybatis3,and it worked good.

Then I found that many SQLs will be written like this:

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

We don't need repeat as a programmer!

So,Can we defined a genric dao or mapper to avoid this repeat? Provide a demo is better.

Some links can help is kindly too.

It bothers me for a long time,need a hand.

I want to write my code like this:

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>

Call in my service layer like this: // Please**NOTICE**:method select is defined in GenericMapper.

TestService.java:

public TestMapper testMapper;

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

Just a few minutes ago,Someone said we can use a Interceptor interface. And I am trying now.

Thanks!

--jackson

jackson
  • 21
  • 1
  • 4
  • Please find SO question http://stackoverflow.com/questions/25055276/reusing-dynamic-sql-fragments – Karthik Prasad Aug 04 '14 at 06:22
  • Maybe I can't desc my goal.I mean using a parent Interface which can provide common method(select,update,insert,delete,etc...) and my mapperInterface just extend it. Someone tell that we can using 'Interceptor',I am trying.If it is ok,I will publish here.Thank you very much. – jackson Aug 04 '14 at 07:14

3 Answers3

0

One of the options is to use mybatis-generator.

0

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

I think this tutorial has exactly what you are looking for. I am not sure what version of Java (or editor config) he is running but I had to add on the Dao methods and suppress the unchecked castings (T) and raw types warnings to get it work on eclipse mars 2 using java 8.

corlaez
  • 1,352
  • 1
  • 15
  • 30
0

I know I might be late but this library from google will address your issue. I have been using it in over 10 projects.

RayGdhrt
  • 1
  • 2