How do you configure mapping relationships using annotations in MyBatis?

In MyBatis, mapping relationships can be configured using annotations such as @Select, @Insert, @Update, @Delete for SQL statements, and @Results, @Result, @ResultMap for result mapping.

Here is an example of configuring mapping relationships using annotations:

@Mapper
public interface UserMapper {
    
    @Select("SELECT * FROM users WHERE id = #{id}")
    @Results({
        @Result(property = "id", column = "id"),
        @Result(property = "name", column = "name")
    })
    User getUserById(Long id);
    
    @Insert("INSERT INTO users(id, name) VALUES(#{id}, #{name})")
    void insertUser(User user);
    
    @Update("UPDATE users SET name = #{name} WHERE id = #{id}")
    void updateUser(User user);
    
    @Delete("DELETE FROM users WHERE id = #{id}")
    void deleteUser(Long id);
}

In the example above, SQL statements are configured using @Select, @Insert, @Update, @Delete annotations, and result mapping relationships are configured using @Results, @Result annotations. A UserMapper interface is defined, which includes methods for retrieving, inserting, updating, and deleting users, with the corresponding SQL statements and result mapping relationships configured through annotations.

广告
Closing in 10 seconds
bannerAds