mybatis mapper配置的方法是什么
MyBatis的Mapper配置方法包括以下两种方式:
- XML配置文件:在XML配置文件中定义Mapper接口与SQL语句的映射关系。通常,这种方式需要在MyBatis的主配置文件中引入Mapper配置文件,并通过namespace属性将Mapper接口与XML配置文件关联起来。
示例:
<!-- MyBatis主配置文件 -->
<configuration>
...
<mappers>
<mapper resource="com/example/mapper/ExampleMapper.xml"/>
</mappers>
</configuration>
<!-- ExampleMapper.xml -->
<mapper namespace="com.example.mapper.ExampleMapper">
<select id="selectById" resultType="com.example.entity.Example">
SELECT * FROM example WHERE id = #{id}
</select>
</mapper>
- 注解方式:通过在Mapper接口的方法上使用注解,直接定义SQL语句。这种方式不需要编写额外的XML配置文件。
示例:
public interface ExampleMapper {
@Select("SELECT * FROM example WHERE id = #{id}")
Example selectById(int id);
}
这两种方式可以根据具体的项目需求和开发习惯选择使用。
相关问答