- 问题
问题
Java程序员面对的最痛苦的事情之一就是在Java代码中嵌入SQL语句。这么来做通常是由于SQL语句需要动态来生成-否则可以将它们放到外部文件或者存储过程中。正如你已经看到的那样,MyBatis在它的XML映射特性中有一个强大的动态SQL生成方案。但有时在Java代码内部创建SQL语句也是必要的。此时,MyBatis有另外一个特性可以帮到你,在减少典型的加号,引号,新行,格式化问题和嵌入条件来处理多余的逗号或 AND 连接词之前。事实上,在Java代码中来动态生成SQL代码就是一场噩梦。例如:
- String sql = "SELECT P.ID, P.USERNAME, P.PASSWORD, P.FULL_NAME, "
- "P.LAST_NAME,P.CREATED_ON, P.UPDATED_ON " +
- "FROM PERSON P, ACCOUNT A " +
- "INNER JOIN DEPARTMENT D on D.ID = P.DEPARTMENT_ID " +
- "INNER JOIN COMPANY C on D.COMPANY_ID = C.ID " +
- "WHERE (P.ID = A.ID AND P.FIRST_NAME like ?) " +
- "OR (P.LAST_NAME like ?) " +
- "GROUP BY P.ID " +
- "HAVING (P.LAST_NAME like ?) " +
- "OR (P.FIRST_NAME like ?) " +
- "ORDER BY P.ID, P.FULL_NAME";