Skip to content

Instantly share code, notes, and snippets.

@jeffgbutler
Last active December 30, 2021 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffgbutler/5df477b4f72f5461a8cc32fb7cf4669b to your computer and use it in GitHub Desktop.
Save jeffgbutler/5df477b4f72f5461a8cc32fb7cf4669b to your computer and use it in GitHub Desktop.
MyBatis Dynamic SQL Limit and Offset
@Select({
"${selectStatement}",
"LIMIT #{parameters.limit} OFFSET #{parameters.offset}"
})
@ResultMap("TLecturesResult")
List<TLectures> selectByExampleWithLimitAndOffset(SelectStatementProvider selectStatement);
@Test
public void selectByExampleWithLimitAndOffset() throws JsonProcessingException {
SelectStatementProvider selectStatement = select(id, ispublish)
.from(TLecturesDynamicSqlSupport.TLectures)
.where(id, isEqualTo("id"))
.orderBy(ispublish.descending())
.build()
.render(RenderingStrategy.MYBATIS3);
selectStatement.getParameters().put("limit", 1);
selectStatement.getParameters().put("offset", 1);
List<TLectures> tLectures = tLecturesMapper.selectByExampleWithLimitAndOffset(selectStatement);
tLectures.forEach(
(tLecture) -> {
try {
objectMapper.writeValueAsString(tLectures);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
);
}
@Flyingblu
Copy link

This gist does not work any more, since the parameters are in an unmutable map. Is there new ways to set the parameters? Or is there better ways to achieve this function?

Thank you!

@jeffgbutler
Copy link
Author

The library now supports limit and offset directly, so you don't need this workaround anymore.

Are you using this pattern for something else?

@jeffgbutler
Copy link
Author

This directory contains an example of a better pattern for modifying the parameters and generated SQL: https://github.com/mybatis/mybatis-dynamic-sql/tree/master/src/test/java/examples/paging

@Flyingblu
Copy link

Thank you so much for the example. It really inspires me.

The problem with the library support is that both limit() and offset() return a finisher object. I cannot use both limit and offset functions in one statement. Is there any way I didn't discover?

@Flyingblu
Copy link

Turns out I really missed something. Sorry for taking your time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment