MyBatis通用Mapper,Service

在使用国内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>




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值