1、定义一个Page类
public class Page<T> {
private int offset;
private int size;
private T model;
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public T getModel() {
return model;
}
public void setModel(T model) {
this.model = model;
}
}
2、定义一个BaseDao接口
public interface BaseDao<T> {
List<T> findBatch(T obj, int offset, int size);
}
3、定义一个默认的实现类DefaultBaseDao
public abstract class DefaultBaseDao<T> extends SqlMapClientDaoSupport implements BaseDao<T> {
protected Class<?> getGenerictClass(Class<?> clazz, int i) {
ParameterizedType parameterizedType = (ParameterizedType) clazz.getGenericSuperclass();
Object genericClass = parameterizedType.getActualTypeArguments()[i];
if (genericClass instanceof ParameterizedType) { // 处理多级泛型
return (Class<?>) ((ParameterizedType) genericClass).getRawType();
} else if (genericClass instanceof GenericArrayType) { // 处理数组泛型
return (Class<?>) ((GenericArrayType) genericClass).getGenericComponentType();
} else {
return (Class<?>) genericClass;
}
}
protected Class<?> getEntityClass() {
return getGenerictClass(this.getClass(), 0);
}
protected String getName() {
return getEntityClass().getSimpleName();
}
@Override
public List<T> findBatch(T obj, int offset, int size) {
Page<T> page = new Page<>();
page.setModel(obj);
page.setOffset(offset);
page.setSize(size);
Map<String, Object> condition = new HashMap<>();
condition.put("page", page);
List<T> list =getSqlMapClientTemplate().queryForList(getName()+".findBatch", condition);
return list;
}
//其他通用增删改查操作
}
4、定义一个实体类的DAO接口,如
public interface UserDao extends BaseDao<User> {
//该实体类特有的数据库操作
}
5、定义实体类DAO接口的实现类,如
public class UserDaoImpl extends DefaultBaseDao<User> implements UserDao {
//该实体类特有的数据库操作
}
6、User.xml中的查询语句
<select id="findBatch" parameterClass="map" resultClass="User">
SELECT * from USER where age = #page.model.age# limit #page.offset#, #page.size#
</select>
7、定义一个基本测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:spring-config.xml"})
public class BaseTest {
protected static Logger LOGGER = LoggerFactory.getLogger(BaseTest.class);
}
public class UserDaoTest extends BaseTest {
@Autowired
private UserDao userDao;
@Test
public void findBatch(){
User user = new User();
user.setAge(10);
userDao.findBatch(user,1,10);
}
}