Hibernate / MyBatis Interview questions
How do you write a basic SELECT statement in MyBatis?
A basic SELECT statement in MyBatis is defined inside a <select> element within a Mapper XML file, specifying an id matching a Mapper interface method, along with the parameter type it accepts and the result type it returns.
<select id="selectUsersByStatus" resultType="com.example.model.User"> SELECT id, name, email, status FROM users WHERE status = #{status} </select>
public interface UserMapper { List<User> selectUsersByStatus(String status); }
MyBatis automatically infers that a method returning List<User> should collect every matching row into a list, while a method declared to return a single User would expect the query to return at most one matching row; the resultType attribute tells MyBatis which class to map each row's columns onto, using column names matched (by default) against matching Java bean property names.
Statements can also be written using annotations directly on the interface method instead of XML — @Select("SELECT ... WHERE status = #{status}") — which is convenient for simple queries, though XML remains the more common choice for anything involving dynamic SQL or complex result mapping, since annotation-based SQL becomes unwieldy for non-trivial statements.
More Related questions...