MyBatis提供了注解配置的方式來簡化映射文件的編寫,通過注解可以直接在Java類中定義SQL語句和映射關系,而不需要額外的映射文件。以下是MyBatis注解配置的詳細介紹:
@Select("select * from user where id = #{id}")
User selectUserById(int id);
@Insert("insert into user(name, age) values(#{name}, #{age})")
void insertUser(User user);
@Select("select * from user where name = #{name} and age = #{age}")
User selectUserByNameAndAge(@Param("name") String name, @Param("age") int age);
@Results({
@Result(property = "name", column = "user_name"),
@Result(property = "age", column = "user_age")
})
@Select("select user_name, user_age from user where id = #{id}")
User selectUserById(int id);
@Results({
@Result(property = "name", column = "user_name"),
@Result(property = "age", column = "user_age")
})
@Select("select user_name, user_age from user where id = #{id}")
@ResultMap("userResultMap")
User selectUserById(int id);
通過以上介紹,可以看出MyBatis的注解配置方式能夠簡化開發過程,同時也提高了代碼的可讀性和維護性。在實際項目中,可以根據具體需求選擇合適的配置方式來使用MyBatis的注解功能。