java mybatis 增删改查 通配式接口开发

本文介绍了如何在Java项目中实现代码复用,通过创建基类接口`BaseDao`和`CrudService`,结合Mybatis-Plus的接口实现,简化了DAO和Service层的操作。示例展示了如何定义`LpProductDao`接口并实现增删改查功能,以及在Service层的抽象类`CrudService`中注入并使用这些接口。
摘要由CSDN通过智能技术生成

前言:实现代码复用,简化代码是非常有必要的,我觉得jeesite这个开源项目非常不错,代码中使用的技术非常全面,而且是一个完整的项目,基本包含了项目的所有知识点,大家有兴趣可以到官网看看,地址在这

现在项目基本的分层一般有 service,dao,entity,web,utils 等,java 有些属性非常适合去开发公共的接口,例如继承,封装,多态,抽象类,泛型等。

目前主流使用的是springboot+mybatis技术,关于mybatis也有一些常用的接口实现,例如mybatis-plus 里面也是有一些现成的接口实现。

这里用自己的方式实现。

dao 层

public interface BaseDao<T> {

    int deleteByPrimaryKey(Integer id);

    int insert(T record);

    int insertSelective(T record);

    T selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(T record);

    int updateByPrimaryKey(T record);
}
public interface LpProductDao extends BaseDao<LpProduct> {

}

对应的mapper xml文件添加上。

service 层

package com.fengdu.service.base;

import com.fengdu.dao.base.BaseDao;
import org.springframework.beans.factory.annotation.Autowired;

public  class BaseService{


}

package com.fengdu.service.base;

import com.fengdu.dao.base.BaseDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Transactional(readOnly = false)
public  abstract class CrudService <D extends BaseDao<T>,T extends Object> extends BaseService {

    @Autowired
    protected  D dao;


    public int deleteByPrimaryKey(Integer id){
        return dao.deleteByPrimaryKey(id);
    }

    public int insert(T  record){
        return  dao.insert(record);
    }

    public int insertSelective(T record){
        return dao.insertSelective(record);
    }

    public T selectByPrimaryKey(Integer id){
        return dao.selectByPrimaryKey(id);
    }

    public int updateByPrimaryKeySelective(T record){
        return dao.updateByPrimaryKeySelective(record);
    }

    public int updateByPrimaryKey(T record){
        return dao.updateByPrimaryKey(record);
    }


}

package com.fengdu.service.impl;

import com.fengdu.dao.LpProductDao;
import com.fengdu.dao.base.BaseDao;
import com.fengdu.entity.LpProduct;

import com.fengdu.service.base.CrudService;
import org.springframework.stereotype.Service;


@Service("lpProductService")
public class LpProductService extends CrudService<LpProductDao,LpProduct>  {

    

}

这样就可以 比较简洁的方式实现增删改查的调用

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值