GithubHelp home page GithubHelp logo

mybatis / mybatis-dynamic-sql Goto Github PK

View Code? Open in Web Editor NEW
1.1K 1.1K 207.0 26.5 MB

SQL DSL (Domain Specific Language) for Kotlin and Java. Supports rendering for MyBatis or Spring JDBC Templates

Home Page: http://www.mybatis.org/mybatis-dynamic-sql/docs/introduction.html

License: Apache License 2.0

Java 75.59% CSS 0.02% Kotlin 24.38%
functional-programming java-8 kotlin kotlin-dsl mybatis mybatis3 spring-jdbctemplate sql-dsl sql-generation sql-generator

mybatis-dynamic-sql's People

Contributors

dependabot-preview[bot] avatar dependabot[bot] avatar harawata avatar hazendaz avatar hboutemy avatar jeffgbutler avatar joshuajeme avatar kazuki43zoo avatar lazyrichard avatar liuhuagui avatar nise-nabe avatar pelmegov avatar renovate[bot] avatar sicaine avatar teillet29200 avatar xuejiangtao avatar youluzheng avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mybatis-dynamic-sql's Issues

how to self join

when self join
SelectStatementProvider q = select(id, name) .from(UserDynamicSqlSupport.user,"u1") .leftJoin(UserDynamicSqlSupport.user2,"u2").on(UserDynamicSqlSupport.user2.pid,equalTo(id)) .where(id, isGreaterThan(1)) .build() .render(RenderingStrategy.MYBATIS3);
generator sql is
select u2.id, u2.name from t_user u2 left join t_user u2 on u2.id = u2.pid where u2.id > ?

@Results with @SelectProvider error?

`
@Mapper
public interface ViewLogCustomMapper {
@SelectProvider(type = SqlProviderAdapter.class, method = "select")
List<Map<String, Object>> selectMany(SelectStatementProvider selectStatement);

@SelectProvider(type = SqlProviderAdapter.class, method = "select")
@Results({
		@Result(column = "id", property = "viewLog", one = @One(select = "cn.xvkang.primarymapperdynamicsql.ViewLogDynamicSqlMapper.selectByPrimaryKey")),
		@Result(column = "hetong_id", property = "hetong", one = @One(select = "cn.xvkang.primarymapperdynamicsql.HetongDynamicSqlMapper.selectByPrimaryKey")),
		@Result(column = "user_id", property = "userTable", one = @One(select = "cn.xvkang.primarymapperdynamicsql.UserTableDynamicSqlMapper.selectByPrimaryKey")),
		@Result(column = "hetong_category_id", property = "hetongCategory", one = @One(select = "cn.xvkang.primarymapperdynamicsql.HetongCategoryDynamicSqlMapper.selectByPrimaryKey")) })
List<ViewLogAllDto> selectMany2(SelectStatementProvider selectStatement);

}
`
public class ViewLogAllDto {
private ViewLog viewLog;
private UserTable userTable;
private Hetong hetong;
private HetongCategory hetongCategory;
}

java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for cn.xvkang.primarymapperdynamicsql.HetongDynamicSqlMapper.selectByPrimaryKey

what is the namespace?
how can i do this ?

Support Multiple Row Inserts

A multiple row insert is a single insert statement that will insert multiple rows. This is not the same thing as a JDBC batch, but there are some use cases where it can be easier to code than a true batch.

This has been requested several different places including mybatis/generator#470 and #53

MyBatis has made some improvements that make this work better (although there are still difficulties with generated keys). But the underlying MyBatis support is mature enough that we can add support to this library.

How can i do an increment update ?

Hello

I don't find how i can do an update query which increment a field like this :

UPDATE TABLE SET field = field + 10 WHERE condition

Is there a functionnality for that ?

Thank you

why it has two join?

QueryExpressionDSL<SelectModel>.JoinSpecificationFinisher on = SqlBuilder
							.select(StudentDynamicSqlSupport.id, StudentDynamicSqlSupport.name,
									StudentDynamicSqlSupport.idcard)
							.from(StudentDynamicSqlSupport.student).join(StudentRegDynamicSqlSupport.studentReg)
							.on(StudentDynamicSqlSupport.id, SqlBuilder.equalTo(StudentRegDynamicSqlSupport.studentid));
					// build()
					// render(RenderingStrategy.MYBATIS3)
					if ((byIdcard) && (byRegCode) && (byExamcode)) {
						if (StringUtils.isBlank(examcodeCellString) || StringUtils.isBlank(regCodeCellString)
								|| StringUtils.isBlank(idcardCellString)) {
							errorMsgStringBuilder.append(" 准考证号不能为空 报名号不能为空 身份证号不能为空 ");
							isDataFormatOk = false;
						} else {
							on.where(StudentDynamicSqlSupport.idcard, SqlBuilder.isEqualTo(idcardCellString))
									.and(StudentRegDynamicSqlSupport.examnumber,
											SqlBuilder.isEqualTo(examcodeCellString))
									.and(StudentRegDynamicSqlSupport.regcode, SqlBuilder.isEqualTo(regCodeCellString));
						}
					} else if ((!byIdcard) && (byRegCode) && (byExamcode)) {
						if (StringUtils.isBlank(examcodeCellString) || StringUtils.isBlank(regCodeCellString)) {
							errorMsgStringBuilder.append(" 准考证号不能为空 报名号不能为空  ");
							isDataFormatOk = false;
						} else {
							on.where(StudentRegDynamicSqlSupport.examnumber, SqlBuilder.isEqualTo(examcodeCellString))
									.and(StudentRegDynamicSqlSupport.regcode, SqlBuilder.isEqualTo(regCodeCellString));
						}
					} else if ((byIdcard) && (!byRegCode) && (byExamcode)) {
						if (StringUtils.isBlank(examcodeCellString) || StringUtils.isBlank(idcardCellString)) {
							errorMsgStringBuilder.append(" 准考证号不能为空 身份证号不能为空 ");
							isDataFormatOk = false;
						} else {
							on.where(StudentDynamicSqlSupport.idcard, SqlBuilder.isEqualTo(idcardCellString)).and(
									StudentRegDynamicSqlSupport.examnumber, SqlBuilder.isEqualTo(examcodeCellString));
						}
					} else if ((byIdcard) && (byRegCode) && (!byExamcode)) {
						if (StringUtils.isBlank(idcardCellString) || StringUtils.isBlank(regCodeCellString)) {
							errorMsgStringBuilder.append("  报名号不能为空 身份证号不能为空 ");
							isDataFormatOk = false;
						} else {
							on.where(StudentDynamicSqlSupport.idcard, SqlBuilder.isEqualTo(idcardCellString))
									.and(StudentRegDynamicSqlSupport.regcode, SqlBuilder.isEqualTo(regCodeCellString));
						}
					} else if ((!byIdcard) && (!byRegCode) && (byExamcode)) {
						if (StringUtils.isBlank(examcodeCellString)) {
							errorMsgStringBuilder.append(" 准考证号不能为空  ");
							isDataFormatOk = false;
						} else {
							on.where(StudentRegDynamicSqlSupport.examnumber, SqlBuilder.isEqualTo(examcodeCellString));
						}
					} else if ((byIdcard) && (!byRegCode) && (!byExamcode)) {
						if (StringUtils.isBlank(idcardCellString)) {
							errorMsgStringBuilder.append("  身份证号不能为空 ");
							isDataFormatOk = false;
						} else {
							on.where(StudentDynamicSqlSupport.idcard, SqlBuilder.isEqualTo(idcardCellString));
						}
					} else if ((!byIdcard) && (byRegCode) && (!byExamcode)) {
						if (StringUtils.isBlank(regCodeCellString)) {
							errorMsgStringBuilder.append(" 报名号不能为空  ");
							isDataFormatOk = false;
						} else {
							on.where(StudentRegDynamicSqlSupport.regcode, SqlBuilder.isEqualTo(regCodeCellString));
						}
					}
					if (isDataFormatOk) {
						SelectStatementProvider selectStatementProvider = on.build().render(RenderingStrategy.MYBATIS3);
						List<Student> students = studentDynamicSqlMapper.selectMany(selectStatementProvider);
						if (students.size() == 1) {
							studentId = students.get(0).getId();
							student = students.get(0);
						} else {
							errorMsgStringBuilder.append(" 此考生不存在  ");
							isDataFormatOk = false;
						}
					}

2019-06-27 14:45:01.513 DEBUG 19673 --- [io-18080-exec-1] c.x.m.S.selectMany : ==> Preparing: select student.id, student.name, student.idcard from student join student_reg on student.id = student_reg.studentId join student_reg on student.id = student_reg.studentId
2019-06-27 14:45:01.520 DEBUG 19673 --- [io-18080-exec-1] c.x.m.S.selectMany : ==> Parameters:
2019-06-27 14:45:01.818 INFO 19673 --- [io-18080-exec-1] o.s.b.f.xml.XmlBeanDefinitionReader : Loading XML bean definitions from class path resource [org/springframework/jdbc/support/sql-error-codes.xml]
org.springframework.jdbc.BadSqlGrammarException:

Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Not unique table/alias: 'student_reg'

The error may exist in cn/xvkang/mapperdynamicsql/StudentDynamicSqlMapper.java (best guess)

The error may involve cn.xvkang.mapperdynamicsql.StudentDynamicSqlMapper.selectMany-Inline

The error occurred while setting parameters

SQL: select student.id, student.name, student.idcard from student join student_reg on student.id = student_reg.studentId join student_reg on student.id = student_reg.studentId

Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Not unique table/alias: 'student_reg'

; bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Not unique table/alias: 'student_reg'
at org.springframework.jdbc.support.SQLExceptionSubclassTranslator.doTranslate(SQLExceptionSubclassTranslator.java:91)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:82)
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:73)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:446)
at com.sun.proxy.$Proxy85.selectList(Unknown Source)
at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:230)
at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:139)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:76)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59)
at com.sun.proxy.$Proxy97.selectMany(Unknown Source)
at cn.xvkang.service.impl.ExcelAutoLuquServiceImpl.excelAutoLuqu(ExcelAutoLuquServiceImpl.java:211)
at cn.xvkang.controller.ExcelAutoLuquController.excelAutoLuqu(ExcelAutoLuquController.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:854)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:765)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at cn.xvkang.securiy.ImageValidateCodeFilter.doFilterInternal(ImageValidateCodeFilter.java:38)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:347)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:263)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:798)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:808)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Not unique table/alias: 'student_reg'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:944)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3978)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3914)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2530)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2683)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2495)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1903)
at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1242)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114)
at com.sun.proxy.$Proxy119.execute(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.ibatis.logging.jdbc.PreparedStatementLogger.invoke(PreparedStatementLogger.java:59)
at com.sun.proxy.$Proxy120.execute(Unknown Source)
at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:63)
at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:79)
at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:63)
at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:326)
at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109)
at com.github.pagehelper.PageInterceptor.intercept(PageInterceptor.java:108)
at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:61)
at com.sun.proxy.$Proxy116.query(Unknown Source)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:433)

Ability to perform merge update

Is it possible to perform update by joining with another table? I don't see such a capability.
Can someone help with this? I don't want to do sub query as I need to update multiple columns from other table.

UPDATE Products
SET end_date = other.end_date
FROM Products me
JOIN #updates other
ON (me.id = other.id)

Add Utility Functions to Enhance *ByExample Support

This is inspired by mybatis/generator#472

Currently, the mapper interfaces generated by MyBatis Generator are a bit inconsistent. With the *ByExample methods, the user is required to code build().render(...) with every use. None of the other generated methods require this.

This change will introduce specialized functions that will enable a change to the code generated by MyBatis Generator. Ultimately it will allow a user to write a simpler lambda expression for a where clause. This will make client code more consistent and cleaner, and will place less burden on the user.

There will be a corresponding change in MyBatis Generator to use these new functions.

It's not possible to have a group by clause directly after a where clause

Hello,

I encounter a problem with a simple query : i want to do
SELECT field FROM table WHERE id = 1 GROUP BY field

so i write my query like this :
select(field).from(table).where(id, isEqualTo(1)).groupBy(field);

But after the where clause, there's no groupBy method.

In the QueryExpressionDSL class, the where clause return an QueryExpressionWhereBuilder which contain only "union", "orderBy" clause but not "groupBy", so i can't use a group by clause without having an order by or union clause before

Make the "column" function of SqlColumn static

Hello,

It'll be great if the column function of the SqlColumn class was static :

Personnaly, i prefer duplicate the "table" parameter on each call of column :
public static final SqlTable table = new SqlTable("table'); public final SqlColumn<Integer> id = SqlTable.column(table , "id", JDBCType.INTEGER); public final SqlColumn<String> firstName = SqlTable.column(table , "first_name", JDBCType.VARCHAR); public final SqlColumn<String> lastName = SqlTable.column(table , "last_name", JDBCType.VARCHAR); public final SqlColumn<Date> birthDate = SqlTable.column(table , "birth_date", JDBCType.DATE); public final SqlColumn<Boolean> employed = SqlTable.column(table , "employed", JDBCType.VARCHAR, "examples.simple.YesNoTypeHandler"); public final SqlColumn<String> occupation = SqlTable.column(table , "occupation", JDBCType.VARCHAR);

rather than dupliate all the field because the column function need "this" on the code for getting the table object :
`public static final SimpleTable simpleTable = new SimpleTable();
public static final SqlColumn id = simpleTable.id;
public static final SqlColumn firstName = simpleTable.firstName;
public static final SqlColumn lastName = simpleTable.lastName;
public static final SqlColumn birthDate = simpleTable.birthDate;
public static final SqlColumn employed = simpleTable.employed;
public static final SqlColumn occupation = simpleTable.occupation;

public static final class SimpleTable extends SqlTable {
    public final SqlColumn<Integer> id = column("id", JDBCType.INTEGER);
    public final SqlColumn<String> firstName = column("first_name", JDBCType.VARCHAR);
    public final SqlColumn<String> lastName = column("last_name", JDBCType.VARCHAR);
    public final SqlColumn<Date> birthDate = column("birth_date", JDBCType.DATE);
    public final SqlColumn<Boolean> employed = column("employed", JDBCType.VARCHAR, "examples.simple.YesNoTypeHandler");
    public final SqlColumn<String> occupation = column("occupation", JDBCType.VARCHAR);

    public SimpleTable() {
        super("SimpleTable");
    }
}`

Table name cannot be keywords of mysql.

For example, I create a table named "order".

By default, mybatis dynamic sql will not escape the table name "order" and jdbc will report a error.

org.springframework.jdbc.BadSqlGrammarException: 
### Error updating database.  Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order (id, ' at line 1
##

If it is possible that mybatis dynamic sql escapes table name before execute queries.

My temporary solution is escaping table name in constructor of org.mybatis.dynamic.sql.SqlTable .

import org.mybatis.dynamic.sql.SqlTable;

class OrderSqlTable extends SqlTable {
    OrderSqlTable() {
        super("`order`");
    }
}

Perhaps, it is a feature? It allows developers to customize their SQL? Or better performance?

package org.mybatis.dynamic.sql.insert.render;
...
public class InsertRenderer<T> {
...
    private String calculateInsertStatement(FieldAndValueCollector<T> collector) {
        return "insert into" //$NON-NLS-1$
                + spaceBefore(model.table().name())
                + spaceBefore(collector.columnsPhrase())
                + spaceBefore(collector.valuesPhrase());
    }

Updating a field with a subquery value

Hello, it's me again

Sorry for the creation of so many issues, I'm migrating a big project to your library and suddenly I see the shortcomings of it

Is it possible to update a field of a table with a subquery ? (i don't see such a thing) :
UPDATE table SET field = (SELECT field FROM table2 WHERE id = x) WHERE id = x

Support for for handling duplicates?

I'm using MyBatis Dynamic SQL with MySQL, and would like to know whether there are any methods to handle duplicates, such that I can do something similar to:

INSERT INTO ...... ON DUPLICATE KEY UPDATE...
or
INSERT IGNORE INTO...

Thanks! :)

select selective

   QueryExpressionDSL<MyBatis3SelectModelAdapter<List<UserEntity>>> dsl = userEntityMapper.selectDistinctByExample();

    WhereDSL whereDSL = null;

    String query = CommonUtil.valueOf(param.get("province"));
    if (StringUtils.isNotBlank(query)) {
        dsl.where(UserEntityDynamicSqlSupport.province, isEqualTo(query));
    }

    query = CommonUtil.valueOf(param.get("city"));
    if (StringUtils.isNotBlank(query)) {
        dsl.where(UserEntityDynamicSqlSupport.city, isEqualTo(query));
    }
    return dsl.build().execute();

how can i use dynamic-sql like below:

     <where>
        <if test="province != null and province != ''">
            and d.province = #{province,jdbcType=VARCHAR}
        </if>
        <if test="city != null and city != ''">
            and d.city = #{city,jdbcType=VARCHAR}
        </if>
        <if test="area != null and area != ''">
            and d.area = #{area,jdbcType=VARCHAR}
        </if>
    </where>

there are any example?

why generator two table name ?

@Override
	public PageImpl<Signup> selectAll(Map<String, Object> params, Integer pageNum, Integer pageSize) {
		QueryExpressionDSL<SelectModel>.QueryExpressionWhereBuilder where = SqlBuilder
				.select(SignupDynamicSqlSupport.signup.allColumns()).from(SignupDynamicSqlSupport.signup, "signup")
				.where(SignupDynamicSqlSupport.id, SqlBuilder.isGreaterThan(0));
		String name = (String) params.get("name");
		if (StringUtils.isNotBlank(name)) {
			where.and(SignupDynamicSqlSupport.name, SqlBuilder.isLike("%" + name + "%"));
		}

		String phone = (String) params.get("phone");
		if (StringUtils.isNotBlank(phone)) {
			where.and(SignupDynamicSqlSupport.phone, SqlBuilder.isLike("%" + phone + "%"));
		}

		String census = (String) params.get("census");
		if (StringUtils.isNotBlank(census)) {
			where.and(SignupDynamicSqlSupport.census, SqlBuilder.isEqualTo(census));
		}
		String birthdayStart = (String) params.get("birthdayStart");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		if (StringUtils.isNotBlank(birthdayStart)) {
			try {
				where.and(SignupDynamicSqlSupport.birthdayDate,
						SqlBuilder.isGreaterThanOrEqualTo(sdf.parse(birthdayStart)));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		String birthdayEnd = (String) params.get("birthdayEnd");
		if (StringUtils.isNotBlank(birthdayEnd)) {
			try {
				where.and(SignupDynamicSqlSupport.birthdayDate, SqlBuilder.isLessThanOrEqualTo(sdf.parse(birthdayEnd)));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		String createTimeAsc = (String) params.get("createTimeAsc");
		if (StringUtils.isNotBlank(createTimeAsc)) {
			if ("1".equals(createTimeAsc)) {
//				where.orderBy(SignupDynamicSqlSupport.createTime.descending());
			} else if ("0".equals(createTimeAsc)) {
				where.orderBy(SignupDynamicSqlSupport.createTime.descending());
			}

		}

		PageHelper.startPage(pageNum, pageSize);
		List<Signup> selectByExample = signupDynamicSqlMapper
				.selectMany(where.build().render(RenderingStrategy.MYBATIS3));
		PageImpl<Signup> pageImpl = new MyPageImpl<Signup>(selectByExample, new PageRequest(pageNum - 1, pageSize),
				((com.github.pagehelper.Page<Signup>) selectByExample).getTotal());
		return pageImpl;
	}

; bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select signup.* from signup signup where signup.id > 0 order by create_time DESC' at line 1] with root cause

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select signup.* from signup signup where signup.id > 0 order by create_time DESC' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_211]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_211]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_211]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_211]
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at com.mysql.jdbc.Util.getInstance(Util.java:408) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:944) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3978) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3914) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2530) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2683) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2495) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1903) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1242) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at sun.reflect.GeneratedMethodAccessor114.invoke(Unknown Source) ~[na:na]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_211]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_211]
at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114) ~[tomcat-jdbc-8.5.40.jar:na]
at com.sun.proxy.$Proxy126.execute(Unknown Source) ~[na:na]
at sun.reflect.GeneratedMethodAccessor114.invoke(Unknown Source) ~[na:na]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_211]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_211]
at org.apache.ibatis.logging.jdbc.PreparedStatementLogger.invoke(PreparedStatementLogger.java:59) ~[mybatis-3.4.6.jar:3.4.6]
at com.sun.proxy.$Proxy127.execute(Unknown Source) ~[na:na]
at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:63) ~[mybatis-3.4.6.jar:3.4.6]
at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:79) ~[mybatis-3.4.6.jar:3.4.6]
at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:63) ~[mybatis-3.4.6.jar:3.4.6]
at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:326) ~[mybatis-3.4.6.jar:3.4.6]

Does it support "paging" feature?

I didn't saw any methods like 'limit' or 'offset' in org.mybatis.dynamic.sql.sqlBuilder... Does it support "paging" feature natively or can be extend to support?

Support for custom rendering conditions

In the latest version, only simple rendering condition judgments are supported, such as IsEqualToWhenPresent for non-null values.However, for String types, in some cases we expect not only non-null, but also non-empty can not be rendered, such as front-end query parameters, empty String means unconditional. So, i hope the SqlBuilder can support custom rendering conditions . The example i used now:

public class IsEqualToIf<T> extends IsEqualTo<T> {

    private Predicate<T> renderCondition;

    protected IsEqualToIf(Supplier<T> valueSupplier, Predicate<T> renderCondition) {
        super(valueSupplier);
        this.renderCondition = Objects.requireNonNull(renderCondition);
    }

    @Override
    public boolean shouldRender() {
        return renderCondition.test(value());
    }

    public IsEqualToIf<T> of(Supplier<T> valueSupplier, Predicate<T> renderCondition) {
        return new IsEqualToIf<>(valueSupplier, renderCondition);
    }
}
public class IsEqualToIfNotEmpty extends IsEqualToIf<String> {

    protected IsEqualToIfNotEmpty(Supplier<String> valueSupplier, Predicate<String> renderCondition) {
        super(valueSupplier, renderCondition);
    }

    public static IsEqualToIfNotEmpty of(String value) {
        return new IsEqualToIfNotEmpty(() -> value, val -> val != null && !"".equals(val.trim()));
    }
}

updateByExample how to use it ?

Integer execute = hetongDynamicSqlMapper.updateByExample(null)
    .set(HetongDynamicSqlSupport.name).equalTo(hetong.getName())
    .set(HetongDynamicSqlSupport.remark).equalTo(hetong.getRemark())
    .set(HetongDynamicSqlSupport.hetongCategoryId).equalTo(hetong.getHetongCategoryId())
    .set(HetongDynamicSqlSupport.imageFilenames).equalTo(hetong.getImageFilenames())
    .where(HetongDynamicSqlSupport.id, SqlBuilder.isEqualTo(hetong.getId()))
    .build()
    .execute();

    return execute;

log NullPointException
how to use updateByExample

support select all

instead of using
select(a,b,c,d,e)
.from(mytable)...

i want to use select(all).from(mytable)...
especially when my table have lots of columns.

Enhance to support spring-batch integration

I am trying to leverage this library for a spring-batch based project. While many of the examples work for traditional invocations, the way Spring-Batch calls function cause the behavior to be a little different.

I'm not sure where these enhancements would be best suited based on the dependencies they would bring in, but I will suggest they be added here and let the maintainers determine which library/libraries they should be absorbed into.

After much trial and error, here are the classes, and tweaks to the examples that need to be added to make the integrations work:

  • SqlProviderAdapter needs to have the method parameters annotated with @Param. I chose statement for the parameter name, but whatever is chosen needs to also be used in the example. This is needed so the batch item reader properly passes the statement to the mapper and the provider class call.
import org.apache.ibatis.annotations.Param;
import org.mybatis.dynamic.sql.select.render.SelectStatementProvider;
import org.mybatis.dynamic.sql.util.SqlProviderAdapter;

public class BatchSqlProviderAdapter extends SqlProviderAdapter
{
	@Override
	public String select(@Param("statement") SelectStatementProvider selectStatement)
	{
		return super.select(selectStatement);
	}
}
  • The example for SimpleTableMapper would be updated to have the select method parameters also annotated with @Param("statement")
  • The MyBatisCursorItemReader<T> needs an extension class that looks like this:
import java.util.HashMap;
import java.util.Map;

import org.mybatis.dynamic.sql.select.render.SelectStatementProvider;
import org.mybatis.spring.batch.MyBatisCursorItemReader;

public class MyBatisDynamicCursorItemReader<T extends Object> extends MyBatisCursorItemReader<T>
{
	@Override
	public void setParameterValues(Map<String, Object> parameterValues)
	{
		Map<String, Object> parameters = new HashMap<>();
		
		parameters.putAll(parameterValues);
		
		if(parameterValues.containsKey("statement"))
		{
			SelectStatementProvider statement = (SelectStatementProvider)parameterValues.get("statement");
			parameters.put("parameters", statement.getParameters());
		}
		
		super.setParameterValues(parameters);
	}
}

I've put together a very simple example project here

how can i use order by asc

`@Override
public PageImpl selectAll(Map<String, Object> params, Integer pageNum, Integer pageSize) {
QueryExpressionDSL.QueryExpressionWhereBuilder where = SqlBuilder
.select(SignupDynamicSqlSupport.signup.allColumns()).from(SignupDynamicSqlSupport.signup, "signup")
.where(SignupDynamicSqlSupport.id, SqlBuilder.isGreaterThan(0));
String name = (String) params.get("name");
if (StringUtils.isNotBlank(name)) {
where.and(SignupDynamicSqlSupport.name, SqlBuilder.isLike("%" + name + "%"));
}

	String phone = (String) params.get("phone");
	if (StringUtils.isNotBlank(phone)) {
		where.and(SignupDynamicSqlSupport.phone, SqlBuilder.isLike("%" + phone + "%"));
	}

	String census = (String) params.get("census");
	if (StringUtils.isNotBlank(census)) {
		where.and(SignupDynamicSqlSupport.census, SqlBuilder.isEqualTo(census));
	}
	String birthdayStart = (String) params.get("birthdayStart");
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	if (StringUtils.isNotBlank(birthdayStart)) {
		try {
			where.and(SignupDynamicSqlSupport.birthdayDate,
					SqlBuilder.isGreaterThanOrEqualTo(sdf.parse(birthdayStart)));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	String birthdayEnd = (String) params.get("birthdayEnd");
	if (StringUtils.isNotBlank(birthdayEnd)) {
		try {
			where.and(SignupDynamicSqlSupport.birthdayDate, SqlBuilder.isLessThanOrEqualTo(sdf.parse(birthdayEnd)));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	String createTimeAsc = (String) params.get("createTimeAsc");
	if (StringUtils.isNotBlank(createTimeAsc)) {
		if ("1".equals(createTimeAsc)) {

// where.orderBy(SignupDynamicSqlSupport.createTime.descending());
} else if ("0".equals(createTimeAsc)) {
where.orderBy(SignupDynamicSqlSupport.createTime.descending());
}

	}

	PageHelper.startPage(pageNum, pageSize);
	List<Signup> selectByExample = signupDynamicSqlMapper
			.selectMany(where.build().render(RenderingStrategy.MYBATIS3));
	PageImpl<Signup> pageImpl = new MyPageImpl<Signup>(selectByExample, new PageRequest(pageNum - 1, pageSize),
			((com.github.pagehelper.Page<Signup>) selectByExample).getTotal());
	return pageImpl;
}

`
SignupDynamicSqlSupport.createTime only have descending,not have ascending?

Unable to automatically update ID propery using autogenerated insert() method

I'm using mybatis generator with target runtime MyBatis3DynamicSql and ANNOTATEDMAPPER java client generator options.

Previously I had the following insert() annotated method (manually written):

@Insert({"insert into header (create_date, modify_date, dealID, timestamp, orgId, ecmHeadFolder) VALUES (#{createDate}, #{modifyDate}, #{dealid}, #{timestamp}, #{orgid}, #{ecmheadfolder})"})
@Options(useGeneratedKeys=true, keyColumn = "id")
void simpleInsert(Header header);

In this case Header was supplied with a proper ID property right after insert() method call which was desired behavior. Header entity has a Long id field that is mapped like id BIGSERIAL PRIMARY KEY.

Now I try to use autogenerated mappers and dynamic SQL approach. After generation I received insert() method with the following implementation (@Options were added later, manually):

@InsertProvider(type=SqlProviderAdapter.class, method="insert")
@Options(useGeneratedKeys=true, keyColumn = "id")
int insert(InsertStatementProvider<Header> insertStatement);

I expected that either insert will return ID after insertion (tried to use long) or it will update ID field in the entity class automatically (like it was before or like it happens for the XML based implementation)

<insert id="insert" useGeneratedKeys="true" keyProperty="id" keyColumn="id">

Nothing expected happened and new autogenerated insert() method simply returns number of updated rows (created in our case).

Please suggest me a way how to achieve automatic ID set for entity using autogenerated keys using autogenerated mappers.

PS Tried @SelectKey using nextval() and id sequence, didn't help.

Support for return type List<Map<String,Object>>

When I need a multi-table query, I have to define the fields of one entity class in the other entity class, which is quite inconvenient.
Is it possible to provide a method that returns type List<Map<String,Object>> in Mappers?
the corresponding XML looks like this:

<select id=”selectMany” resultType=”java.util.HashMap”>  
    select * from table
</select>  

Where clause generator don't name some parameters as expected when using standalone or / and methods

Hi,

I wanted to generated where clause, and I used the multiple paramerters sample, where we can tell mybatis how to name the parameter.

The problem is that I need to use this kind of query :
WhereClauseProvider whereClause = where(Record.critRecStart, isBetween(DateTime.now().minusYears(2)).and(DateTime.now())) .and(Record.critChannelNumber, isEqualTo(1L), or(Record.critChannelNumber, isEqualTo(10L))) .build().render(RenderingStrategy.MYBATIS3, "whereClauseProvider");

Here, you can see, that I am using a 'standalone' or method call.

The resulted where clause is :

"where rec_start between #{whereClauseProvider.parameters.p1,jdbcType=TIMESTAMP,typeHandler=com.thalesgroup.vpro.db.typehandlers.DateTimeTypeHandler} and #{whereClauseProvider.parameters.p2,jdbcType=TIMESTAMP,typeHandler=com.thalesgroup.vpro.db.typehandlers.DateTimeTypeHandler} and (channel_number = #{whereClauseProvider.parameters.p3,jdbcType=INTEGER} or channel_number = #{parameters.p4,jdbcType=INTEGER})"

And we can see that the last parameter (p4) is not prefixed with whereClauseProvider, resulting in a query that can't be executed.

Does it support @one or @many annotation?

Thank you for checking.
Here is my question.
For example, order table has a field userid,and I need the order info and user info in the user table at the same time.
I tried to do like this.
@Result(column="userid", property="userid", jdbcType=JdbcType.BIGINT, one=@One(select="com.xxx.dao.UserMapper.selectByPrimaryKey",fetchType=FetchType.LAZY)
defined attribute user in model class 'Order'
private User user;
It doesn't work.
What should I do?

Dynamic select with zero to many filter criteria

Hi guys, I'm curious how I can dynamically define query with zero to dozen filter criteria in where clause using query dsl.

Right now i'm using where(id, isNotNull()) first and then adding and and or conditions for every column in filter criteria. Is there any other ways to do it?

Does it support inner query ?

I want to construct query like below
SELECT inner_table.*, ROW_NUMBER() OVER (ORDER BY colum1 DESC) AS RN FROM ( SELECT colum1 FROM test ) inner_table

Is it possible ?

How to feed Dynamic fields for dynamic queries and JSONB fields

This is not an issue. Rather I am seeking help. Apologies, if this is not the right platform to ask questions.

SelectStatementProvider example provided in Mybatis website starts as follows.

SelectStatementProvider selectStatement = select(id, animalName, bodyWeight, brainWeight)

If the fields are not known in advance and fields are available as list of String parameter from a class, how can I fill that in the above select(...) ?
Also, I am using PostgreSQL with JSONB column. How can I use JSONB field in the select(....) ?

I know how to select JSOB field using plain SQL statements. But, not sure whether SelectStatementProvider supports it.

How to get new record id

when I use insert method, how can I get the new record id?
for example:

Employee record = new Employee();
record.setFirstName("Joe");

InsertStatementProvider insertStatement = insert(record)
    .into(employee)
    .map(firstName).toProperty("firstName")
    .build()
    .render(RenderingStrategy.MYBATIS3);

int rows = mapper.insert(insertStatement);

The result of insert method is rows of inserted recored, but I want to get the id of the new record.

Problems on integration with spring mvc

Data config

@Configuration
@MapperScan(basePackages = {"path-to-mapper"}, annotationClass = Mapper.class)
@EnableTransactionManagement
public class DataConfig {
    @Bean(destroyMethod = "close")
    public DataSource dataSource() {
        HikariConfig hikariConfig = new HikariConfig();
        // data-source config ..
        return new HikariDataSource(hikariConfig);
    }

    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();
        return sqlSessionFactory;
    }
}

*mapper.java and *support.java are successfully generated by mbg, when invoking mapper's(accessed via @Autowired query method, this error occurs:

 Request processing failed; nested exception is org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): ${mapper's query method}

looks like it complains about missing mapper xml, but it should not need it.
I've tried demo without spring and it works fine, do I miss some configurations?

MyBatis3RenderingStrategy is incompatible with myBatis3 ?

Hello,

Thank you for this great library.

I test it for some days but i encounter a problem : when i use the MyBatis3RenderingStrategy like the samples, i can't use easily like the myBatis3 functionnal call :

With MyBatis dynamic sql, i can write a query like :
select id from table where id = #{id}

with a function like :
public Dto selectById(@Param(value = "id") Integer id);

myBatis automatically map the id parameter, that's great !

But with the new DynamicSql MyBatis3RenderingStrategy, the same query is formatted like this :
select id from table where id = #{parameters.p1,jdbcType=INTEGER}

and myBatis is unable to map the id parameter.

I can use a Parameter bean containing the sql query and the id parameter, but i prefer to use parameters on function call rather than using a new bean for each call.

So i have wrote my own Renderer like this :
public class SimpleMyBatis3RenderingStrategy extends RenderingStrategy { @Override public String getFormattedJdbcPlaceholder(BindableColumn<?> column, String prefix, String parameterName) { return "#{"+ ((SqlColumn) column).name() + "}"; } }

It's not very pretty, i know, but it works.

Have you planned to make this kind of Renderer in future ?
Or maybe there is another method to use for generating a compatible query with the functionnal calling ?

Add Ability to Call "where()" with no Parameters

This will be useful for cases when there is complex logic associated with a where clause. A good example is seen in #100 where there is complex logic associated with creating a search and the where clause could be generated many different ways. We should support a usage like this:

QueryExpressionDSL<SelectModel>.QueryExpressionWhereBuilder builder = select(person.allColumns())
    .from(person)
    .where();

if (someCondition) {
  builder.and(id, isEqualto(3));
}

if (anotherCondition) {
  builder.and(firstName, isNull());
}

SelectStatementProvider selectStatement = builder.build().render(RenderingStrategy.MYBATIS3);

This should render properly regardless of whether all conditions, or none, are satisfied.

support for self-join 

when i use :
SqlBuilder.select(...) .from(table, "a") .join(table, "b")
the result is :
select ... from table b join table b on b.id = b.id

Support count(distinct xx)

mybatis-dynamic-sql:1.1.1
oracle jdk1.8
l want to execute the following query
select count( distinct company_code) from table
but selectDistinct function belong to FromGatherer
count function belong to BasicColumn
I can't construct a query through mybatis-dynamic-sql。
I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.
Does it support?
and What should I do if support ?
Thanks in advance.

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.