What’s the difference between @Select and @Results annotations in MyBatis?
In MyBatis, both @Select
and @Results
annotations are used to define SQL queries and map the results to Java objects, but they serve different purposes.
@Select
@Select
annotation is used to define a SQL SELECT
statement directly in your mapper interface. It specifies the query that will be executed when the method is called.@Select("SELECT * FROM users WHERE id = #{id}")
User getUserById(int id);
@Results
@Results
annotation is used to define how the results of a query should be mapped to the properties of a Java object. It is typically used in conjunction with @Select
or other query annotations.@Select("SELECT id, username, email FROM users WHERE id = #{id}")
@Results({
@Result(property = "userId", column = "id"),
@Result(property = "userName", column = "username"),
@Result(property = "userEmail", column = "email")
})
User getUserById(int id);
@Select
to define the SQL query.@Results
to define how the result set maps to the Java object properties.In practice, if your query results match the property names of your Java object, you may not need to use @Results
at all, as MyBatis can automatically map the results based on naming conventions. However, @Results
becomes essential when you need to customize the mapping.