如何在mybatis的xml文件中,include另一个xml文件中的sql

目的是为了提高xml文件中sql的复用性。

跟着一些帖子试下来都不行,特意发帖求助。

必须要在 java 中定义一下,并且加上 @Mapper 注解才行。要不然 mybatis 是不会解析这个 .xml 文件的。

写动态sql呀

你的需求是什么?描述一下。

对于多个xml文件需要同时引用一段相同的 可以在某个xml 中定义这个 sql 代码片段,在需要引用的地方使用全称引用即可,例子如下: ShareMapper.xml id,name CustomMapper.xml

  • select from t
  • <mapper namespace="com.mapper.Mapper1"> 
    
        <select id="getEntity1" resultType="Entity1"> 
        select * form entity1 
        </select> 
    </mapper> 

     

    <mapper namespace="com.mapper.Mapper2"> 
    
        <resultMap id="entity2ResultMap" type="Entity2"> 
        <association property="entity1" 
           column="entity1_id" 
           javaType="Entity1" 
           select="com.mapper.Mapper1.getEntity1"/> 
        </resultMap> 
    
    </mapper> 

     

    sql片段 如果要引用别的xml文件中的sql片段则要写上该xml文件的namespace全名.sql片段id值