mybatis mapper接口怎么配置

小億
97
2023-12-21 05:05:14

MyBatis Mapper接口的配置需要完成以下幾個(gè)步驟:

  1. 創(chuàng)建Mapper接口:首先需要?jiǎng)?chuàng)建一個(gè)Mapper接口,該接口中定義了需要執(zhí)行的SQL語(yǔ)句和對(duì)應(yīng)的方法。例如,可以在接口中定義一個(gè)查詢用戶信息的方法:
public interface UserMapper {
    User getUserById(int id);
}
  1. 創(chuàng)建Mapper XML文件:在resources目錄下創(chuàng)建一個(gè)與Mapper接口同名的XML文件,例如UserMapper.xml。在該文件中配置SQL語(yǔ)句和與Mapper接口中方法的映射關(guān)系。例如,可以配置查詢用戶信息的SQL語(yǔ)句:
<!-- UserMapper.xml -->
<mapper namespace="com.example.mapper.UserMapper">
    <select id="getUserById" resultType="com.example.model.User">
        SELECT * FROM user WHERE id = #{id}
    </select>
</mapper>
  1. 配置Mapper接口掃描:在MyBatis的配置文件中配置Mapper接口的掃描路徑,MyBatis會(huì)自動(dòng)掃描并注冊(cè)Mapper接口。例如,可以在mybatis-config.xml文件中配置Mapper接口的包路徑:
<!-- mybatis-config.xml -->
<configuration>
    <mappers>
        <package name="com.example.mapper"/>
    </mappers>
</configuration>
  1. 使用Mapper接口:在需要使用Mapper接口的地方,通過(guò)注入或者使用Spring等框架進(jìn)行依賴注入,然后即可使用Mapper接口中定義的方法執(zhí)行SQL語(yǔ)句。例如,在Service層中注入U(xiǎn)serMapper接口并調(diào)用getUserById方法:
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    
    public User getUserById(int id) {
        return userMapper.getUserById(id);
    }
}

這樣就完成了MyBatis Mapper接口的配置。注意,Mapper接口的命名規(guī)范和XML文件的命名規(guī)范需要按照約定來(lái)做,以便MyBatis能夠正確地進(jìn)行映射和配置。

0