Skip to content
cjbi edited this page Jan 9, 2020 · 8 revisions

MyBatis-Ext - 方便易用的MyBatis增强扩展

  • 作者:cjbi
  • 当前版本:1.5.0

简介

MyBatis-Ext是MyBatis的增强扩展,简化了MyBatis对单表增删改查的操作,提供通用的增删改查,支持函数式编程,支持分页查询,支持用户自定义通用方法,SQL无注入,集成简单,只做增强不做修改。

快速开始

Maven

<dependency>
        <groupId>tech.wetech.mybatis</groupId>
        <artifactId>mybatis-ext-core</artifactId>
      <!--  使用最新的正式版本:
        https://repo1.maven.org/maven2/tech/wetech/mybatis/
         -->
       <version>LATEST_VERSION</version>
 </dependency>

Java

编写一个Pojo类,与数据库表对应

//Mybatis-ext使用了Jpa的注解,目前实现了@Table、@Id、@Column、@Transient、@Version,未来考虑支持更多Jpa特性
@Table(name = "weshop_user")//指定表名,必须
public class User {
    @Id//指定Primary Key,必须
    private Integer id;
    private String password;
    @Column(name = "gender")//指定指定字段映射,非必须,不指定字段名驼峰转下划线
    private String gender;
    @Transient//忽略该属性
    private String pageSize;
    @Transient
    private String pageNumber;
    @LogicDelete//逻辑删除
    private Integer delFlag;
    //此处省略getter,setter
}

继承BaseMapper接口

public interface UserMapper extends BaseMapper<User> {
}

在Java中使用

//新建一个连接池方式的数据源工厂
        PooledDataSourceFactory pooledDataSourceFactory = new PooledDataSourceFactory();
        //设置数据源
        Properties properties = new Properties();
        properties.setProperty("driver", "<JDBC驱动>");
        properties.setProperty("url", "<JDBC URL>");
        properties.setProperty("username", "<用户名>");
        properties.setProperty("password", "<密码>");
        pooledDataSourceFactory.setProperties(properties);
        DataSource dataSource = pooledDataSourceFactory.getDataSource();
        //新建会话工厂
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("development", transactionFactory, dataSource);
        Configuration configuration = new ExtConfiguration(environment); //此处使用ExtConfiguration
        configuration.setLogImpl(Log4jImpl.class);
        //添加Mapper映射
        configuration.addMapper(UserMapper.class);
        //此处使用ExtSqlSessionFactoryBuilder
        SqlSessionFactory sqlSessionFactory = new ExtSqlSessionFactoryBuilder().build(configuration);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //根据主键查询
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.selectByPrimaryKey(1);
Clone this wiki locally