GithubHelp home page GithubHelp logo

abel533 / mapper Goto Github PK

View Code? Open in Web Editor NEW
7.3K 348.0 1.6K 2.13 MB

Mybatis Common Mapper - Easy to use

Home Page: https://mybatis.io

License: MIT License

Java 99.33% FreeMarker 0.67%
mybatis-plugin mybatis mapper

mapper's Issues

批量插入,回写ID只有一个

通用接口方法,返回list中只回写了一个ID字段

public interface InsertListMapper {
/**
* 批量插入,支持数据库自增字段,支持回写
*
* @param recordList
* @return
*/
@options(useGeneratedKeys = true, keyProperty = "id")
@InsertProvider(type = SpecialProvider.class, method = "dynamicSQL")
int insertList(List recordList);
}

关于使用通用mapper和分页插件进行分页时,查询出来的数据重复的问题

我使用PageHelper分页,发现调用selectByExampleAndRowBounds这个方法后,本应返回10条数据,但是实际返回了20条,数据是重复的。我调试代码,发现在pagehelper的SqlUtil类中,第499行的Object result = invocation.proceed();方法走了两遍,导致下面的page.addAll((List)result);方法加了两遍数据。不能确定是哪里引起的问题。pageHelper的版本是4.1.6,mapper的版本是3.3.8.

select方法报错

ProviderSqlSource.class
85行 sql = (String) providerMethod.invoke(providerType.newInstance(), parameterObject);

BaseSelectProvider.class中没有空的构造函数,无法实例化

继承通用mapper不能使用spring进行扫描

我封装了一个基类,这个基类继承通用mapper:

package com.yuantu.core.base;
import java.util.List;
import tk.mybatis.mapper.common.Mapper;
import com.yuantu.domain.BaseDomain;
public interface BaseMapper<M extends BaseDomain, VO> extends Mapper<M> {
}

然后业务mapper继承这个基类:

package com.yuantu.mapper;
import com.yuantu.core.base.BaseMapper;
import com.yuantu.domain.DemoKey;
import com.yuantu.domain.DemoKeyVo;
public interface DemoKeyMapper extends BaseMapper<DemoKey, DemoKeyVo> {\
}

如果将自己封装的BaseMapper和业务DemoKeyMapper,都进行spring的basepackage扫描:

<property name="basePackage" value="com.yuantu.mapper" />

虽然源码中有基类扫描的判断:

……
        if (this.mapperClass == getMapperClass(ms.getId())) {
            throw new RuntimeException("请不要配置或扫描通用Mapper接口类:" + this.mapperClass);
        }
……

但并不能拦截到,而是往下继续运行出现如下错误:

Caused by: java.lang.RuntimeException: 调用方法异常:java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class
    at tk.mybatis.mapper.mapperhelper.MapperHelper.setSqlSource(MapperHelper.java:247)
    at tk.mybatis.mapper.mapperhelper.MapperHelper.processConfiguration(MapperHelper.java:303)
    at tk.mybatis.spring.mapper.MapperFactoryBean.checkDaoConfig(MapperFactoryBean.java:23)
    at org.springframework.dao.support.DaoSupport.afterPropertiesSet(DaoSupport.java:44)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
    ... 42 more

水平不够,因为这个问题,弄了一下午,哎,都是泪……
不知道这个是BUG,还是就应该如此,希望可以将错误提示改进的更加友好一些。

like and notLike 小问题

Example.Criteria andLike
Example.Criteria andNotLike
一不小心会掉坑里,因为这两个方法并没有给value自动加上%%
其实可以重载个方法加个参数表示前面加/后面加/both

保存或修改时,如果参数内容含$符号,会报错

保存或修改时,如果参数内容含$符号,会报错
nested exception is org.apache.ibatis.exceptions.PersistenceException: \n### Error updating database. Cause: java.lang.IllegalArgumentException: Illegal group reference\n### Cause: java.lang.IllegalArgumentException: Illegal group reference

希望增加example可以构建自定义的查询条件

oracle下,假如CREATE_DATE字段是DATE类型,用example构建查询条件,当传入的参数为java.util.Date时,oracle会自动使用to_timestamp函数,这样就不会走CREATE_DATE这个字段的索引,而且使用druid打印出的可执行的sql是有问题的,
所以希望增加一个方法,可以传入一个自定义的子句,方便使用oracle的函数之类的

MyBatis Generator的主键生成问题(丢失GeneratedValue注解)

你好,
我读了你的文档,觉得你的Mapper很实用。刚刚在研究你的demo的时候,我做了一些修改(我的表有些不是直接以Id为主键的)

        <table tableName="user_info">
            <generatedKey column="user_id" sqlStatement="Mysql" identity="true"/>
        </table>
        <table tableName="%">
            <generatedKey column="id" sqlStatement="Mysql" identity="true"/>
        </table>

然后我发现在UserInfo的model中是这样的

    @Id
    @Column(name = "user_id")
    // 下面这句注解没有自动生成,导致返回不了user_id主键值
    //@GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer userId;

我的配置是不是有什么问题,有没有什么方法可以让它生成一下?
我的环境是win7x64,java 7。
谢谢
=)

批量插入失败

批量插入List,插入失败: nested exception is org.apache.ibatis.builder.BuilderException: Error invoking SqlProvider method (tk.mybatis.mapper.provider.SpecialProvider.dynamicSQL). Cause: java.lang.InstantiationException: tk.mybatis.mapper.provider.SpecialProvider

For循环单独插入Model是没问题的。

数据源是 mysql

字段大小写,关键字

版本3.3.8
SELECT ID,op_emp_id,op_emp_name,op_dept_id,op_dept_name,create_time,apply_id,DESC FROM gz_sys_log,导致sql查询失败?能不能设置一下关于字段大小写,还有加上 ` 符号,mysql数据库

java+oracle数据库调用updateByPrimaryKeySelective、insertSelective等方法抛异常,无效的列类型: 1111

nested exception is org.apache.ibatis.type.TypeException: Could not set parameters for mapping: ParameterMapping{property='remark', mode=IN, javaType=class java.lang.String, jdbcType=null, numericScale=null, resultMapId='null', jdbcTypeName='null', expression='null'}. Cause: org.apache.ibatis.type.TypeException: Error setting null for parameter #2 with JdbcType OTHER . Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. Cause: java.sql.SQLException: 无效的列类型: 1111
六月 23, 2016 11:37:13 上午 org.apache.catalina.core.StandardWrapperValve invoke

generator插件能不能在生成的Model类中加上列名常量定义?

例如User类有列名id、username等,那么User类里面生成列名的常量定义:
public class User { ...... static public final String ID = "id"; static public final String USERNAME = "username"; ...... }
这样方便其他地方用到,如Criteria类的方法需要传property,就可以引用这些常量。

或者 是否有其他插件可以实现这个功能?

怎样定义不查询的字段

不知道mapper.xml中的select方法是否重写通用Mapper中的select

我有一个user表,就是不想在查询的时候把password查出来

请问有什么好的办法吗?

Number类型0值不会加到条件里

Entity t = new Entity ();
t.setStatus(0);
PageInfo<Entity > pageInfo = service.queryByPage(t, 1, 20);

结果是where条件里不会带上status这个属性,不仅仅是查询有这个问题

表字段已经用驼峰式命名时的一个问题~~

表字段,本身已经是驼峰式命名,如orderId,
在generator.xml中,我这样写
生成...table tableName="order_settlement_daily" domainObjectName="OrderSettlementDaily" ... 》
《property value="true" name="useActualColumnNames"/》

即使用真实字段名,生成的bean属性即为orderId

问题:
因为bean属性与真实字段名一致,所以没有生成@column注释,
所以,拼接sql时,会拼成order_id,导致失败。
我现在是修改了MapperCommentGenerator.java,
//if (!column.equals(introspectedColumn.getJavaProperty())) {
//@column
field.addAnnotation("@column(name = "" + column + "")");
//}
把判断注释掉了,始终生成@column注解,就没问题了。

首次使用查询date类型的时候报错了

2016-06-30 10:36:09.807 DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 145 debug - ==>  Preparing: SELECT ID,CREATE_DATE,UPDATE_DATE,NAME,AGE FROM TEST WHERE ID = ? AND CREATE_DATE = ? AND UPDATE_DATE = ? AND NAME = ? AND AGE = ? 
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.type.TypeException: Could not set parameters for mapping: ParameterMapping{property='createDate', mode=IN, javaType=class java.util.Date, jdbcType=null, numericScale=null, resultMapId='null', jdbcTypeName='null', expression='null'}. Cause: org.apache.ibatis.type.TypeException: Error setting non null for parameter #2 with JdbcType null . Try setting a different JdbcType for this parameter or a different configuration property. Cause: java.lang.ClassCastException: java.lang.Long cannot be cast to java.util.Date

    protected Long id;
    @Column(name = "CREATE_DATE")
    protected Date createDate;    // 创建日期
    @Column(name = "UPDATE_DATE")
    protected Date updateDate;    // 更新日期
    @Transient
    protected Boolean newRecord;
    private String name;
    private int age;

CREATE TABLE `TEST` (
`id`  int(15) NOT NULL ,
`name`  varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
`age`  tinyint(4) NOT NULL ,
`create_date`  datetime NOT NULL ,
`update_date`  datetime NOT NULL ,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci
ROW_FORMAT=DYNAMIC
;

如果我把date类型的删掉了 报不一样的错
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.type.TypeException: Could not set parameters for mapping: ParameterMapping{property='name', mode=IN, javaType=class java.lang.String, jdbcType=null, numericScale=null, resultMapId='null', jdbcTypeName='null', expression='null'}. Cause: org.apache.ibatis.type.TypeException: Error setting non null for parameter #2 with JdbcType null . Try setting a different JdbcType for this parameter or a different configuration property. Cause: java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String
麻烦帮忙看下这个问题,还有我想问下,自动生成的参数类型是不是能匹配上 比如我int类型不加引号,字符串加引号 谢谢

字段为关键字

当字段为关键字时,插入语句会报错。
实体类必须写成

@Column(name` = "`desc`")
private String desc;

实体类中Blob类型报错

mybatis源码中TypeHandlerRegistry.class中register了
register(JdbcType.LONGVARBINARY, new BlobTypeHandler());
register(JdbcType.BLOB, new BlobTypeHandler());

但是我实体类中定义
Blob test;
test的type是interface java.sql.Blob或者class com.mysql.jdbc.Blob
而不是Blob
会导致java.lang.IllegalStateException: No typehandler found for property test

使用Mapper专用的MyBatis Generator插件生成mapper时报错

版本信息:

mybatis-generator-core版本1.3.4
mapper版本3.3.8

generatorConfig.xml配置:(省略其他MBG原生配置)

<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers" value="tk.mybatis.mapper.common.Mapper"/>
 </plugin>

错误信息:

Exception in thread "main" java.lang.AbstractMethodError: tk.mybatis.mapper.generator.MapperCommentGenerator.addModelClassComment(Lorg/mybatis/generator/api/dom/java/TopLevelClass;Lorg/mybatis/generator/api/IntrospectedTable;)V
    at org.mybatis.generator.codegen.mybatis3.model.BaseRecordGenerator.getCompilationUnits(BaseRecordGenerator.java:70)
    at org.mybatis.generator.codegen.mybatis3.IntrospectedTableMyBatis3Impl.getGeneratedJavaFiles(IntrospectedTableMyBatis3Impl.java:233)
    at org.mybatis.generator.config.Context.generateFiles(Context.java:721)
    at org.mybatis.generator.api.MyBatisGenerator.generate(MyBatisGenerator.java:269)
    at org.mybatis.generator.api.MyBatisGenerator.generate(MyBatisGenerator.java:139)
    at Gen.GenMain.main(GenMain.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

如何在自定义的Mapper对应的Provider中,获取Condition(Example)条件和entityClass等参数?

如何在自定义的Mapper对应的Provider中,获取Condition(Example)条件和entityClass等参数?

public class MyMybatisProvider extends MapperTemplate{

    private ExampleProvider exampleProvider;

    public MyMybatisProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
        super(mapperClass, mapperHelper);
        exampleProvider = new ExampleProvider(mapperClass, mapperHelper);
    }

    /**
     * 
     * @desc 根据Condition条件,查询未(逻辑)删除的数据
     * @param ms
     * @return
     */
    public String selectNoDeleteByCondition(MappedStatement ms) {

        // 我想在这里增加Condition的条件,
        //  如果Condition为NULL时还需要获取entityClass来构造Condition
        return exampleProvider.selectByExample(ms);
    }

}

spring-boot中启动后,getEntityTable为null

EntityTable entityTable = entityTableMap.get(entityClass);
if (entityTable == null) {
throw new RuntimeException("无法获取实体类" + entityClass.getCanonicalName() + "对应的表名!");
}

能否解决下,在热部署(restart classLoader)的状态下,entityTable是null的情况?

可否在@Column上支持 updatable

建议:
@column上支持 updatable,为false时,不参与update。

缘由:
由于数据库表里有update_date字段,由MYSQL自动生成更新时间。所以要限制业务层的改写。

现象:
在update数据时,SPRING MVC 通过ModelAttribute进行 MERGE,然后就永远是第一次更新的时间了。

UUID主键

如果主键策略为UUID,新增后无法获取到生成的主键

3.3.8之后, 列名的大小写出现问题.

3.3.7是正确如下:
Preparing: INSERT INTO app_user ( app_user_id,app_user_name,app_user_gender,app_user_image_url,create_time ) VALUES( ?,?,?,?,? )
而到了3.8:
Preparing: INSERT INTO app_user ( APP_uSER_iD,APP_uSER_nAME,APP_uSER_gENDER,APP_uSER_iMAGE_uRL,CREATE_tIME ) VALUES( ?,?,?,?,? )

example查询时出现order by语句错误

一个很简单的查询:

        Example example = new Example(City.class);
        example.createCriteria().andEqualTo("state", "河北");
        List<City> list = mapper.selectByExample(example);

拼出来的SQL,后面带了orderBy这个实体的地址,不知道为什么要解析orderby 我看了源码感觉可能是判断是否有orderby的问题,实际上我根本没有配置order by语句,但是还是打印出来了这样的语句.源码如下:

### SQL: SELECT Id, name, state FROM city WHERE (state = ?) order by tk.mybatis.mapper.entity.Example$OrderBy@603256ca
Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server

见SqlHelper类514行:

    /**
     * example查询中的orderBy条件,会判断默认orderBy
     *
     * @return
     */
    public static String exampleOrderBy(Class<?> entityClass) {
        StringBuilder sql = new StringBuilder();
        sql.append("<if test=\"orderByClause != null\">");
        sql.append("order by ${orderByClause}");
        sql.append("</if>");
        String orderByClause = EntityHelper.getOrderByClause(entityClass);
        if (orderByClause.length() > 0) {
            sql.append("<if test=\"orderByClause == null\">");
            sql.append("ORDER BY " + orderByClause);
            sql.append("</if>");
        }
        return sql.toString();
    }

3.3.7中加上order by的api查询仍报此错误

    @Test
    public void testSelectByExp(){
        Example example = new Example(City.class);
        example.createCriteria().andEqualTo("state", "河北");
 **     example.orderBy("state");** 
        List<City> list = mapper.selectByExample(example);
        System.out.println(list.size());
    }

我的环境如下:
spring 4.2.6
mybatis 3.4.1
mybatis-spring 1.3.0
mapper 3.3.7

Mapper 生成的sql 列名不正确。

为user表创建了一个唯一主键列userid,然而mapper映射出来的sql语句中总是user_id。在任何配置文件中都找不到 user_id这个字段,请问可能是什么原因??

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException:

Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'USER_iD' in 'field list'

The error may exist in com/github/ichenkaihua/mapper/UserMapper.java (best guess)

The error may involve com.github.ichenkaihua.mapper.UserMapper.selectCount-Inline

The error occurred while setting parameters

SQL: SELECT COUNT(USER_iD) FROM user WHERE NAME = ?

Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'USER_iD' in 'field list'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.