tk-mybatis 的使用方法详解

2022-10-18

tkmybatis是在mybatis框架的基础上提供了很多工具,本文就详细的介绍了一下tk-mybatis 的使用方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

tkmybatis是在mybatis框架的基础上提供了很多工具,让开发更加高效,下面来看看这个框架的基本使用,后面会对相关源码进行分析,感兴趣的同学可以看一下,挺不错的一个工具

实现对员工表的增删改查的代码 

java的dao层接口

public interface WorkerMapper extends Mapper<Worker> {
}

实体对象

@Table(name = "worker")
public class Worker {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
 
    @Column(name = "worker_id")
    private String workerId;
 
    private String name;
 
    @Column(name = "org_id")
    private Integer orgId;
 
    private String status;
 
    @Column(name = "role_id")
    private Integer roleId;
 
    // getters and setters ...
    }

以上就是实现对Worker进行增删改查的所有代码,包括选择性更新、插入、删除等,所有的方法列表如下

以后对表字段的添加或修改只需要更改实体对象的注解,不需要修改xml映射文件,如将worker_id改成worker_no

@Column(name = "worker_no")
private String workerNo;

数据源的配置,只需要将org.mybatis.spring.mapper.MapperScannerConfigurer改成tk.mybatis.spring.mapper.MapperScannerConfigurer,然后加一个属性 
,也可不加,因为框架提供了默认实现

    <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <property name="basePackage" value="com.jjs.zanbi.dao" />
        <property name="properties">
            <value>
                mappers=tk.mybatis.mapper.common.Mapper
            </value>
        </property>
    </bean>

通用Service类

/**
 * Created by Kaiwen
 */
@Service
public abstract class CommonServiceImpl<T,PK extends Serializable> implements CommonService<T,PK> {
    /**
     * 泛型注入
     */
    @Autowired
    private Mapper<T> mapper;
 
    public T selectByPrimaryKey(PK entityId) {
 
        return mapper.selectByPrimaryKey(entityId);
    }
 
    public int deleteByPrimaryKey(PK entityId) {
        return mapper.deleteByPrimaryKey(entityId);
    }
 
    public int insert(T record) {
        return mapper.insert(record);
    }
 
    public int insertSelective(T record) {
        return mapper.insertSelective(record);
    }
 
    public int updateByPrimaryKeySelective(T record) {
        return mapper.updateByPrimaryKeySelective(record);
    }
 
    public int updateByPrimaryKey(T record) {
        return mapper.updateByPrimaryKey(record);
    }
 
    public List<T> selectByExample(Example example) {
        return mapper.selectByExample(example);
    }
}

到此这篇关于tk-mybatis 的使用方法详解的文章就介绍到这了,更多相关tk-mybatis使用内容请搜索北冥有鱼以前的文章或继续浏览下面的相关文章希望大家以后多多支持北冥有鱼!

您可能感兴趣的文章:

  • tk.mybatis如何扩展自己的通用mapper
  • 解决tk.mybatis中写自定义的mapper的问题
  • tk.mybatis扩展通用接口使用详解

《tk-mybatis 的使用方法详解.doc》

下载本文的Word格式文档,以方便收藏与打印。