近日做系统,由于选择了mybatis作为后端的ORM,所以在纠结到底用注解annotation的方式好呢,还是使用xml配置的方式。
为此,查询了很多资料。感觉大部分都在推荐xml配置方式,并且我是诚心的去用annotation的,毕竟想顺应时代嘛,结果死活就是找不到。
最后找到了一个方法,其实感觉这个方法是在走我很早以前的老路,在还没使用ORM的时代,我们通常自己来做非空判断并且拼接sql语句
请看代码
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 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 && example.getOrderByClause() != null) {
ORDER_BY(example.getOrderByClause());
}
return SQL();
}
ContactDao
public List searchByExample(Contact contact) {
System.out.println("searchByExampleContact");
ContactExample example = new ContactExample();
ContactExample.Criteria cri = example.createCriteria();
System.out.println(contact.getUsername() + ":" + contact.getPassword());
if (!contact.getUsername().equals("") && contact.getUsername() != null)
cri.andUsernameEqualTo(contact.getUsername());
if (!contact.getPassword().equals("") && contact.getPassword() != null)
cri.andPasswordEqualTo(contact.getPassword());
ContactMapper vcontactMapper = sqlSession
.getMapper(ContactMapper.class);
List returnList = vcontactMapper.selectByExample(example);
return returnList;
}
其实这个也并不说不好,就是觉得怪怪的。而去访问了mybatis的官网,关于动态sql的guide还是推崇xml的方式的
http://mybatis.github.io/mybatis-3/dynamic-sql.html
我持保留意见。我过去一直使用hibernate的,不知道是个人技艺不精还是别的原因。总觉得速度效率上有点滞后。
有愿意讨论了,欢迎过来拍砖。