Mybatis使用Annotation實(shí)現(xiàn)動(dòng)態(tài)參數(shù)和自定義返回對(duì)象查詢(xún)

最近又復(fù)習(xí)了JPA和Hibernate,JPA-hibernate到現(xiàn)在支持自定義對(duì)象和動(dòng)態(tài)參數(shù)查詢(xún)都很復(fù)雜,早應(yīng)該簡(jiǎn)化了。

Mybatis變得如此受歡迎,確實(shí)有原因的。

查詢(xún)語(yǔ)句需要:

a.自定義Object,比如ProductWithTypeName

b.支持根據(jù)動(dòng)態(tài)參數(shù)組裝sql語(yǔ)句

在Mybatis里面實(shí)現(xiàn)這兩個(gè)要求就很簡(jiǎn)單和方便。

我喜歡用注解,不想用xml配置文件,繼續(xù)簡(jiǎn)化和少些代碼。

public class ProductWithTypeName {

private Integer prodectId;

private String productName;

private? Integer typeId;

private String typeName;

1. 實(shí)現(xiàn)方式一

@Select({ "<script>"

? +"select p.id as prodectId, p.name as productName,type.id as typeId,type.name as typeName "

? +"from product p left join product_type type on p.product_type =type.id "

? +"where 1=1"

? +"<if test='pname != null'> AND p.name=#{pname} </if> "

? +"<if test='tname != null'> AND type.name=#{tname} </if>"

? +"</script>"

? })

public List<ProductWithTypeName> queryProductAnnotation(@Param("pname")String

? productName,@Param("tname") String typeName);

根據(jù)參數(shù)動(dòng)態(tài)構(gòu)建查詢(xún)sql也可以寫(xiě)在注解里面,確實(shí)方便。

2.實(shí)現(xiàn)方式二,增加provider

@SelectProvider(type=MerchantManageDaoSqlProvider.class,method="queryProductProvider")

public List<ProductWithTypeName> queryProduct(String productName,String typeName);

public class MerchantManageDaoSqlProvider {

public String queryProductProvider(String productName,String typeName) {

String sql="select p.id as prodectId, p.name as productName,type.id as typeId,type.name as typeName "

+ "from product p left join product_type type on p.product_type =type.id where 1=1 ";

if(StringUtils.isNotBlank(productName)) {

sql+=" and p.name='"+productName+"'";

}

if(StringUtils.isNotBlank(typeName)) {

sql+=" and type.name='"+typeName+"'";

}

return sql;

}

}

這兩種實(shí)現(xiàn)方式都很方便。

Mybatis確實(shí)實(shí)用。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容