abel533 / mapper Goto Github PK
View Code? Open in Web Editor NEWMybatis Common Mapper - Easy to use
Home Page: https://mybatis.io
License: MIT License
Mybatis Common Mapper - Easy to use
Home Page: https://mybatis.io
License: MIT License
selectOne() 是本来就不返回主键,还是说我的配置有问题?
因为包冲突导致,解决方法
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>${tk.mybatis.mapper.version}</version>
<exclusions>
<exclusion>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
</exclusion>
</exclusions>
</dependency>```
我使用PageHelper分页,发现调用selectByExampleAndRowBounds这个方法后,本应返回10条数据,但是实际返回了20条,数据是重复的。我调试代码,发现在pagehelper的SqlUtil类中,第499行的Object result = invocation.proceed();方法走了两遍,导致下面的page.addAll((List)result);方法加了两遍数据。不能确定是哪里引起的问题。pageHelper的版本是4.1.6,mapper的版本是3.3.8.
ProviderSqlSource.class
85行 sql = (String) providerMethod.invoke(providerType.newInstance(), parameterObject);
BaseSelectProvider.class中没有空的构造函数,无法实例化
请在接口中增加批量添加的功能
谢谢
我封装了一个基类,这个基类继承通用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,还是就应该如此,希望可以将错误提示改进的更加友好一些。
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
oracle下,假如CREATE_DATE字段是DATE类型,用example构建查询条件,当传入的参数为java.util.Date时,oracle会自动使用to_timestamp函数,这样就不会走CREATE_DATE这个字段的索引,而且使用druid打印出的可执行的sql是有问题的,
所以希望增加一个方法,可以传入一个自定义的子句,方便使用oracle的函数之类的
你好,
我读了你的文档,觉得你的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数据库
没有问题,jar的版本问题
public static char toUpperAscii(char c) { if (isUppercaseAlpha(c)) { //127 c -= (char) 0x20; } return c; }
if (isUppercaseAlpha(c))
应为if (isLowercaseAlpha(c))
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
Style是控制驼峰的方法,我看java集成中可以通过Config来设置的,Spring集成该如何设置这个属性的
例如User类有列名id、username等,那么User类里面生成列名的常量定义:
public class User { ...... static public final String ID = "id"; static public final String USERNAME = "username"; ...... }
这样方便其他地方用到,如Criteria类的方法需要传property,就可以引用这些常量。
或者 是否有其他插件可以实现这个功能?
如题,criteria.andCondition 是直接字符串 容易sql 注入啊
不知道mapper.xml中的select方法是否重写通用Mapper中的select
我有一个user表,就是不想在查询的时候把password查出来
请问有什么好的办法吗?
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属性与真实字段名一致,所以没有生成@column注释,
所以,拼接sql时,会拼成order_id,导致失败。
我现在是修改了MapperCommentGenerator.java,
//if (!column.equals(introspectedColumn.getJavaProperty())) {
//@column
field.addAnnotation("@column(name = "" + column + "")");
//}
把判断注释掉了,始终生成@column注解,就没问题了。
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类型不加引号,字符串加引号 谢谢
如题 .
因为经常是先用set去重. 如果还要转成List, 其实没有太大的必要
当字段为关键字时,插入语句会报错。
实体类必须写成
@Column(name` = "`desc`")
private String desc;
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
mybatis-generator-core版本1.3.4
mapper版本3.3.8
<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等参数?
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-devtools 工具,EntityTable entityTable = entityTableMap.get(entityClass);获取实体的EntityTable 对象为空。
报错
无法获取实体类 **** 对应的表名
EntityTable entityTable = entityTableMap.get(entityClass);
if (entityTable == null) {
throw new RuntimeException("无法获取实体类" + entityClass.getCanonicalName() + "对应的表名!");
}
能否解决下,在热部署(restart classLoader)的状态下,entityTable是null的情况?
什么时候支持批量插入,是id没自增限制的
建议:
在@column上支持 updatable,为false时,不参与update。
缘由:
由于数据库表里有update_date字段,由MYSQL自动生成更新时间。所以要限制业务层的改写。
现象:
在update数据时,SPRING MVC 通过ModelAttribute进行 MERGE,然后就永远是第一次更新的时间了。
是否有动态表名的使用样例?
如果主键策略为UUID,新增后无法获取到生成的主键
.java 与.xml 放在同一目录 貌似xml 并没有被扫描,xml的中的方法没有被生成代理类
我按照教程没有找到叫做MapperInterceptor的类,版本3.3.6
遇到很奇怪的问题,调用selectByPrimaryKey正常,调用selectByExample(example)时,就报Invalid bound statement (not found)
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( ?,?,?,?,? )
Mysql数据,保存或修改时,如果参数内容含$符号,会报错,希望尽快解决
一个很简单的查询:
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
如题
为user表创建了一个唯一主键列userid,然而mapper映射出来的sql语句中总是user_id。在任何配置文件中都找不到 user_id这个字段,请问可能是什么原因??
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException:
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.