当前程序版本
mybatis-plus-spring-boot3-starter:3.5.8
问题描述
kotlin 使用 KtQueryWrapper 的 select 方法会报空指针异常
原因:
这个select调用了默认方法com.baomidou.mybatisplus.core.conditions.query.Query#select(Predicate
default Children select(Predicate<TableFieldInfo> predicate) {
return this.select(null, predicate);
}
这个默认方法调用对应实现类的
Children select(Class<T> entityClass, Predicate<TableFieldInfo> predicate);
其中 com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper 这个类中关于这个 [select] 的实现被声明为
override fun select(entityClass: Class<T>, predicate: Predicate<TableFieldInfo>): KtQueryWrapper<T>
可以发现其中名为 entityClass 的参数是不可以为null的, kotlin 对此会进行非空校验, 然而调用上面的默认方法将 null 直接传入就导致了 kotlin 报出空指针异常, 我觉得解决办法应该就是屏蔽掉非空校验就行了(如下: 加个 ?)
也可能这个问号会影响别的,不知道,希望能解决.
override fun select(entityClass: Class<T>?, predicate: Predicate<TableFieldInfo>): KtQueryWrapper<T>
测试代码:
package com.example.demo
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class Demo2ApplicationTests {
@set:Autowired
lateinit var studentMapper: StudentMapper
@Test
fun contextLoads() {
val includeFields = listOf(Student::id.name, Student::name.name)
studentMapper.selectList(KtQueryWrapper(Student()).select {
it.field.name in includeFields
})
}
}
详细堆栈日志
java.lang.NullPointerException: Parameter specified as non-null is null: method com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper.select, parameter entityClass
at com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper.select(KtQueryWrapper.kt)
at com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper.select(KtQueryWrapper.kt:35)
at com.baomidou.mybatisplus.core.conditions.query.Query.select(Query.java:78)
at com.example.demo.Demo2ApplicationTests.contextLoads(Demo2ApplicationTests.kt:15)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
Comment From: gaohongf
测试代码改成这样也是一样的,我只要是KtQueryWrapper调用这个方法一定会报错
studentMapper.selectList(KtQueryWrapper(Student()).select { true })
不去查询光是调用也会报错
@SpringBootTest
class Demo2ApplicationTests {
@Test
fun contextLoads() {
KtQueryWrapper(Student()).select { true }
}
}