mybatisplus insert into select
时间: 2023-09-30 08:04:59 浏览: 269
MyBatis-Plus提供了两种方式实现Insert-Select操作:
1. 使用Wrapper进行构造SQL语句
```java
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.select("id", "name", "age")
.eq("deleted", 0)
.orderByDesc("age")
.last("limit 10");
String sql = "insert into user (id, name, age) " +
"select id, name, age from user_copy " +
queryWrapper.getSqlSegment();
int result = userMapper.insert(new User(), new InsertIntoSelectInjector(sql));
```
2. 使用@Insert注解执行原生SQL
```java
@Insert("insert into user (id, name, age) " +
"select id, name, age from user_copy " +
"where deleted = 0 order by age desc limit 10")
int insertBySelect();
```
其中,InsertIntoSelectInjector是一个自定义的Injector实现,用于执行原生SQL。可以参考以下代码:
```java
public class InsertIntoSelectInjector extends AbstractSqlInjector {
private final String sql;
public InsertIntoSelectInjector(String sql) {
this.sql = sql;
}
@Override
public SqlNode inject(SqlNode sqlNode) {
return new InsertIntoSelectNode(sql);
}
private class InsertIntoSelectNode extends AbstractSqlNode {
private final String sql;
public InsertIntoSelectNode(String sql) {
this.sql = sql;
}
@Override
public boolean apply(DynamicContext context) {
context.appendSql(sql);
return true;
}
}
}
```
注意,这种方式需要注意SQL注入的安全问题,建议使用第一种方式。
阅读全文