在使用国内mybatis拓展工具包tk.mybatis和MyBatis Generator的基础上,我们得到了实体类及其自动生成通用的接口,但是仍然需要在每一个service里手动注入dao,基本的CURD还是需要在service里面定义,达不到我们简化开发的要求。这时我们缺少一个BaseService,能够根据泛型自动注入dao,并定义常用的CURD方法,每一个service再继承它,就能达到想要的目的。
BaseService类
package com.wang.ff.util;
import java.io.Serializable;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.common.Mapper;
public abstract class BaseService<D extends Mapper<T>, T extends Serializable> {
@Autowired
protected D dao;
/**
* 通过id查询 实体
* @param id id
* @return 实体
*/
public T selectByPrimaryKey(Long id) {
return this.dao.selectByPrimaryKey(id);
}
/**
* 通过id删除实体
* @param id id
* @return 提示信息
*/
public Integer deleteById(Long id) {
return this.dao.deleteByPrimaryKey(id);
}
public D getDao() {
return dao;
}
public void setDao(D dao) {
this.dao = dao;
}
}
值得注意的是,支持泛型依赖注入是Spring 4.0 RELEASE版本的新特性。
UserService类
package com.wang.ff.entity.sUser.service;
import org.springframework.stereotype.Service;
import com.wang.ff.entity.sUser.domain.SUser;
import com.wang.ff.entity.sUser.persistence.SUserMapper;
import com.wang.ff.util.BaseService;
@Service
public class UserService extends BaseService<SUserMapper, SUser>{
public SUser getUserByName(String userName){
return this.dao.getUserByName(userName);
}
}
Controller
package com.wang.ff.controller;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.wang.ff.entity.sUser.domain.SUser;
import com.wang.ff.entity.sUser.service.UserService;
@Controller
@RequestMapping(value="/user")
public class UserController {
@Resource
private UserService userService;
@RequestMapping(value="/getUser")
public ModelAndView getUser(String userName){
ModelAndView mv = new ModelAndView("user");
SUser user = this.userService.getUserByName(userName);
mv.addObject("user",user);
return mv;
}
}
jsp页面
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Hello world!
</h1>
<p>name:${user.userName };password:${user.password }</p>
</body>
</html>