mybatis的多条件查询案例(动态sql)
近⽇做系统,由于选择了mybatis作为后端的ORM,所以在纠结到底⽤注解annotation的⽅式好呢,还是使⽤xml配置的⽅式。
为此,查询了很多资料。感觉⼤部分都在推荐xml配置⽅式,并且我是诚⼼的去⽤annotation的,毕竟想顺应时代嘛,结果死活就是不到。
最后到了⼀个⽅法,其实感觉这个⽅法是在⾛我很早以前的⽼路,在还没使⽤ORM的时代,我们通常⾃⼰来做⾮空判断并且拼接sql语句
请看代码
jpa mybatis
ContactMapper.java
@SelectProvider(type=ContactSqlProvider.class, method="selectByExample")
@Results({
@Result(column="idcontact", property="idcontact", jdbcType=JdbcType.INTEGER, id=true),
@Result(column="contacttype_idcontacttype", property="contacttypeIdcontacttype", jdbcType=JdbcType.INTEGER),
@Result(column="username", property="username", jdbcType=JdbcType.VARCHAR),
@Result(column="password", property="password", jdbcType=JdbcType.VARCHAR),
@Result(column="userlocale", property="userlocale", jdbcType=JdbcType.VARCHAR),
@Result(column="usersetting", property="usersetting", jdbcType=JdbcType.VARCHAR),
@Result(column="retired", property="retired", jdbcType=JdbcType.BIT),
@Result(column="department_iddepartment", property="departmentIddepartment", jdbcType=JdbcType.INTEGER)
})
List<Contact> selectByExample(ContactExample example);
ContactSqlProvider
public String selectByExample(ContactExample example) {
BEGIN();
if (example != null && example.isDistinct()) {
SELECT_DISTINCT("idcontact");
} else {
SELECT("idcontact");
}
SELECT("contacttype_idcontacttype");
SELECT("username");
SELECT("password");
SELECT("userlocale");
SELECT("usersetting");
SELECT("retired");
SELECT("department_iddepartment");
FROM("contact");
applyWhere(example, false);
if (example != null && OrderByClause() != null) {
ORDER_OrderByClause());
}
return SQL();
}
ContactDao
public List<Contact> searchByExample(Contact contact) {
System.out.println("searchByExampleContact");
ContactExample example = new ContactExample();
ContactExample.Criteria cri = ateCriteria();
System.out.Username() + ":" + Password());
if (!Username().equals("") && Username() != null)
cri.Username());
if (!Password().equals("") && Password() != null)
cri.Password());
ContactMapper vcontactMapper = sqlSession
.getMapper(ContactMapper.class);
List<Contact> returnList = vcontactMapper.selectByExample(example);
return returnList;
}
</pre>其实这个也并不说不好,就是觉得怪怪的。<p>⽽去访问了mybatis的官⽹,关于动态sql的guide还是推崇xml的⽅式的</p><p>mybatis.github.io/mybatis-3    resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</select>
所以,各有利弊吧。当然也有⼤师提醒我说,为什么不⽤JPA。
我持保留意见。我过去⼀直使⽤hibernate的,不知道是个⼈技艺不精还是别的原因。总觉得速度效率上有点滞后。
有愿意讨论了,欢迎过来拍砖。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。