简体   繁体   English

如何使用 mybatis 直接从 java 代码中执行查询?

[英]How to exequte query directly from java code using mybatis?

I need to execute query which has been generated by java code in runtime (not static method).我需要在运行时执行由 java 代码生成的查询(不是静态方法)。 I already know how to build dynamic query by using annotation and static method or using xml mapper, but it is not suitable in my case.我已经知道如何使用注解和静态方法或使用 xml 映射器来构建动态查询,但它不适合我的情况。

Is there any way to execute query from java code directly?有没有办法直接从java代码执行查询?

Mybatis has already this function, but you must use the adapter as follows. Mybatis 已经有这个功能了,但是你必须使用适配器,如下所示。

  1. create an adapter class;创建一个适配器类;

     public class SQLAdapter { String sql; public SQLAdapter(String sql) { this.sql = sql; } public String getSql() { return sql; } public void setSql(String sql) { this.sql = sql; } }
  2. create typeAlias of class SQLAdapter创建类 SQLAdapter 的 typeAlias

<typeAlias alias="sqladapter" type="com.zj.xxx.xxx.SQLAdapter" />

  1. put select tag in each object xml where you need to execute the sql directly.在需要直接执行 sql 的每个对象 xml 中放置选择标记。

     <select id="findRecords" parameterType="SQLAdapter" resultMap="xxxxxResultMap"> ${sql} </select>
  2. call this select method like像这样调用这个选择方法

    String _sql = "select * from table where... order by... limit..."; xxxxx.findRecords(new SQLAdapter(_sql));
  3. Things have been all done.事情都已经做好了。 you can no longer writer complex sql language in the xml file.您不能再在 xml 文件中编写复杂的 sql 语言。 Good Luck.祝你好运。

似乎最好的答案是在这种情况下使用 JDBC。

You can do this using SQL query as literal parameter:您可以使用 SQL 查询作为文字参数来执行此操作:

<select id="findRecords" parameterType="string" resultMap="xxxxxResultMap">  
    ${_parameter}
</select>

You can pass only where clause:您只能通过 where 子句:

<select id="findRecords" parameterType="string" resultMap="xxxxxResultMap">  
    select * from records where ${_parameter}
</select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM