近日做系統,由於選擇了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<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 && example.getOrderByClause() != null) {
ORDER_BY(example.getOrderByClause());
}
return SQL();
}
ContactDao
public List<Contact> 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<Contact> returnList = vcontactMapper.selectByExample(example);
return returnList;
}
</pre>其實這個也並不說不好,就是覺得怪怪的。<p>而去訪問了mybatis的官網,關於動態sql的guide還是推崇xml的方式的</p><p>http://mybatis.github.io/mybatis-3/dynamic-sql.html</p><pre name="code" class="html"><select id="findActiveBlogLike"
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的,不知道是個人技藝不精還是別的原因。總覺得速度效率上有點滯後。
有願意討論了,歡迎過來拍磚。