• 问题

    问题

    Java程序员面对的最痛苦的事情之一就是在Java代码中嵌入SQL语句。这么来做通常是由于SQL语句需要动态来生成-否则可以将它们放到外部文件或者存储过程中。正如你已经看到的那样,MyBatis在它的XML映射特性中有一个强大的动态SQL生成方案。但有时在Java代码内部创建SQL语句也是必要的。此时,MyBatis有另外一个特性可以帮到你,在减少典型的加号,引号,新行,格式化问题和嵌入条件来处理多余的逗号或 AND 连接词之前。事实上,在Java代码中来动态生成SQL代码就是一场噩梦。例如:

    1. String sql = "SELECT P.ID, P.USERNAME, P.PASSWORD, P.FULL_NAME, "
    2. "P.LAST_NAME,P.CREATED_ON, P.UPDATED_ON " +
    3. "FROM PERSON P, ACCOUNT A " +
    4. "INNER JOIN DEPARTMENT D on D.ID = P.DEPARTMENT_ID " +
    5. "INNER JOIN COMPANY C on D.COMPANY_ID = C.ID " +
    6. "WHERE (P.ID = A.ID AND P.FIRST_NAME like ?) " +
    7. "OR (P.LAST_NAME like ?) " +
    8. "GROUP BY P.ID " +
    9. "HAVING (P.LAST_NAME like ?) " +
    10. "OR (P.FIRST_NAME like ?) " +
    11. "ORDER BY P.ID, P.FULL_NAME";