最近又復(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í)用。