While XML configuration remains the predominant approach in MyBatis, annotation-based development offers a streamlined alternative that is widely adopted across other frameworks in the ecosystem.
Defining Mapper Interfaces with Annotations
Annotate methods directly on the interface to specify SQL queries:
public interface UserDao {
@Select("SELECT * FROM users WHERE id = #{id}")
UserEntity findById(int id);
}
Configuring Annotation-Based Mappers
In the MyBatis core configuration file, register the mapper interface instead of an XML mapper:
<mappers>
<mapper class="com.example.dao.UserDao"/>
</mappers>
Executing Queries
@Test
public void testQueryById() {
SqlSession session = SqlSessionFactoryUtil.getSession();
UserDao dao = session.getMapper(UserDao.class);
UserEntity result = dao.findById(1);
System.out.println(result);
session.close();
}
Insert, Update, and Delete Operations
When working with multiple parameters of primitive types or when parameter ambiguity might occur, the @Param annotation becomes essential. For reference types, MyBatis can infer the parameter name, but explicitly using @Param improves clarity and safety.
public interface UserDao {
@Insert("INSERT INTO users VALUES (#{id}, #{username}, #{password})")
int addUser(UserEntity user);
@Delete("DELETE FROM users WHERE id = 10")
int removeUser(int id);
@Update("UPDATE users SET username = #{username} WHERE id = #{id}")
int modifyUser(UserEntity user);
@Select("SELECT * FROM users")
List<UserEntity> fetchAllUsers();
@Select("SELECT * FROM users WHERE id = #{id} AND username = #{name}")
UserEntity findByIdAndName(@Param("id") int id, @Param("name") String name);
}
Test Cases for CRUD Operations
@Test
public void testSelect() {
SqlSession session = SqlSessionFactoryUtil.getSession();
UserDao dao = session.getMapper(UserDao.class);
UserEntity user = dao.findByIdAndName(1, "admin");
System.out.println(user);
session.close();
}
@Test
public void testInsert() {
SqlSession session = SqlSessionFactoryUtil.getSession();
UserDao dao = session.getMapper(UserDao.class);
int rows = dao.addUser(new UserEntity(10, "testuser", "pass123"));
if (rows > 0) {
session.commit();
System.out.println("Insert successful");
}
session.close();
}
@Test
public void testDelete() {
SqlSession session = SqlSessionFactoryUtil.getSession();
UserDao dao = session.getMapper(UserDao.class);
int rows = dao.removeUser(10);
if (rows > 0) {
session.commit();
System.out.println("Delete successful");
}
session.close();
}
@Test
public void testUpdate() {
SqlSession session = SqlSessionFactoryUtil.getSession();
UserDao dao = session.getMapper(UserDao.class);
int rows = dao.modifyUser(new UserEntity(9, "updateduser", "newpass"));
if (rows > 0) {
session.commit();
System.out.println("Update successful");
}
session.close();
}
Enabling Auto-Commit
The exapmles above demonstarte manual transaction commit. MyBatis supports automatic commit configuration through the openSession method:
public static SqlSession getAutoCommitSession() {
return sqlSessionFactory.openSession(true);
}
The openSession method overload enables automatic transaction commit when passed a boolean parameter set to true.