Annotations Instead of XML
Harry
· 11 Sep 2026
· 10 views
An XML-Free Mapper
For simple statements, MyBatis lets you put SQL directly on the interface with annotations - no XML file needed.
public interface CustomerMapper {
@Select("SELECT * FROM customers WHERE id = #{id}")
Customer findById(Long id);
@Select("SELECT * FROM customers WHERE city = #{city}")
List<Customer> findByCity(String city);
@Insert("INSERT INTO customers (name, email, city)
VALUES (#{name}, #{email}, #{city})")
@Options(useGeneratedKeys = true, keyProperty = "id")
void insert(Customer customer);
@Update("UPDATE customers SET city = #{city} WHERE id = #{id}")
int updateCity(@Param("id") Long id, @Param("city") String city);
@Delete("DELETE FROM customers WHERE id = #{id}")
int delete(Long id);
}When Annotations Work Well
- Short, stable CRUD statements.
- No dynamic SQL required.
- You prefer reading SQL next to the method.
When to Keep XML
- Long queries with dynamic SQL and result maps.
- Complex nested associations.
- Report queries over a hundred lines.
XML handles the hard cases; annotations stay tidy for the easy ones. You may mix both per mapper.
Key Points
- @Select, @Insert, @Update, @Delete inline the SQL.
- @Options pulls generated keys into the entity.
- Annotations suit short, static statements.
- Keep XML for dynamic and complex queries.