欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

mybatis中使用InsertProvider注解報錯解決全過程

 更新時間:2022年07月06日 09:38:10   作者:fhqfjfh  
這篇文章主要介紹了mybatis中使用InsertProvider注解報錯解決全過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

使用InsertProvider注解報錯解決

目前項目在使用mybatis,并且是使用注解的方式。

在使用InsertProvider注解的時候報了一下的錯誤:

org.apache.ibatis.builder.BuilderException: Could not find value method on SQL annotation.  Cause: org.apache.ibatis.builder.BuilderException: Error creating SqlSource for SqlProvider. Method........

注解是如下這個樣子的

@InsertProvider(method = "insertlist",type=SqlProvider.class)
?public int insertInnerTable(List list,String dbTable);

思路是要寫一個通用的插入一個集合的方法,但是在執(zhí)行的時候就報了上面的錯誤。

在網(wǎng)上查資料未果。

于是只能自己動手,豐衣足食了。

一步步跟斷點,跟到mybatis了報錯的方法中,發(fā)現(xiàn)了如下的代碼

try {
? ? ? this.sqlSourceParser = new SqlSourceBuilder(config);
? ? ? this.providerType = (Class<?>) provider.getClass().getMethod("type").invoke(provider);
? ? ? providerMethodName = (String) provider.getClass().getMethod("method").invoke(provider);
? ? ? for (Method m : this.providerType.getMethods()) {
? ? ? ? if (providerMethodName.equals(m.getName())) {
? ? ? ? ? if (m.getParameterTypes().length < 2
? ? ? ? ? ? ? && m.getReturnType() == String.class) {
? ? ? ? ? ? this.providerMethod = m;
? ? ? ? ? ? this.providerTakesParameterObject = m.getParameterTypes().length == 1;
? ? ? ? ? }
? ? ? ? }
? ? ? }
? ? } catch (Exception e) {
? ? ? throw new BuilderException("Error creating SqlSource for SqlProvider. ?Cause: " + e, e);
? ? }

注意標(biāo)黃的位置,終于發(fā)現(xiàn)導(dǎo)致錯誤的罪魁禍?zhǔn)琢?,原來是這里限制了參數(shù)的個數(shù),不能操作兩個參數(shù)的啊。

于是將方法以及注解改為如下形式

@InsertProvider(method = "insert",type=SqlProvider.class)
?public int insert(SqlContext sqlContext);
在SqlProvider中對應(yīng)的方法為
public String insert(SqlContext sqlContext){
? ? ? ........
}

至此問題解決

mybatis注解開發(fā)@InsertProvider

插入一條user的數(shù)據(jù),可以直接根據(jù)username和password插入

//insert into user(username,password) values(?,?)
@Insert("insert into user(username,password) values(#{username},#{password})")
void save(User user);

但是如果有一個需求,要求傳入username和password能正常輸入,傳入username、password、id也能夠正常插入,這個時候就可以使用Provider注解。

這個的用法就是可以創(chuàng)建一個方法類,在類里面做判斷,讓mapper里面的查詢方法根據(jù)寫的方法來選擇需要的sql語句。

Userprovider類

import com.sikiedu.springbootssm.entity.User;
public class Userprovider {?? ?
?? ?public String saveUser(User user)
?? ?{
?? ??? ?if(user.getId()==null)
?? ??? ?{
?? ??? ??? ?return "insert into user(username,password) values(#{username},#{password}) ";
?? ??? ?}
?? ??? ?else
?? ??? ?{
?? ??? ??? ?return "insert into user values(#{id},#{username},#{password})";
?? ??? ?}
?? ?}?? ?
}

在這個類里面我們做判斷,選擇需要的sql語句。

mapper的書寫

@InsertProvider(type = Userprovider.class,method="saveUser")
void save (User user);

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論