Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MyBatis/iBatis - reusable sql fragments in a separate SQL Map file?

Tags:

People also ask

How does MyBatis work?

UNPOOLED − For the dataSource type UNPOOLED, MyBatis simply opens and closes a connection for every database operation. It is a bit slower and generally used for the simple applications. POOLED − For the dataSource type POOLED, MyBatis will maintain a database connection pool.

What is resultMap in MyBatis?

The resultMap element is the most important and powerful element in MyBatis. It's what allows you to do away with 90% of the code that JDBC requires to retrieve data from ResultSet s, and in some cases allows you to do things that JDBC does not even support.


I would like to put sql fragments used by several of my SQL Map XML files in a separate file. At the moment, the <sql> elements with these fragments are in one of the mappers together with other elements like <select>, which makes them hard to find.

Can I have a mapper that defines just a few <sql> elements and is not used to generate an implementation to an interface? What would be the correct namespace of this mapper?

This is the SQL Map file with the framents:

<mapper namespace="com.company.project.dao.someDao">      <sql id="whereDate">         WHERE date(`time`) BETWEEN #{startDate} AND #{endDate}     </sql>        <sql id="someOtherSqlFragment">         ...     </sql>      <select id="getSomeData" resultType="SomeClass" parameterType="DateParam" >         SELECT some_column, another_column                   FROM some_table         <include refid="whereDate"/>         <include refid="otherSqlFragment"/>     </select>  </mapper> 

I'd like to separate the elements like this:
First Sql Map file:

<mapper namespace="com.company.project.dao.???">      <sql id="whereDate">         WHERE date(`time`) BETWEEN #{startDate} AND #{endDate}     </sql>        <sql id="someOtherSqlFragment">         ...     </sql>  </mapper> 

Second Sql Map file:

<mapper namespace="com.company.project.dao.someDao">      <select id="getSomeData" resultType="SomeClass" parameterType="DateParam" >         SELECT some_column, another_column                   FROM some_table              <include refid="whereDate"/>         <include refid="otherSqlFragment"/>     </select>  </mapper>