Skip to main content
Hint

This article is generated by AI translation.

Declarative API

The declarative API defines the SQL to execute and the return results by creating Annotated Method. Managing SQL through interfaces keeps query maintenance centralized and code structure clear.

Highlights
  • Focus on abstracting query needs as interfaces, and execute queries using Annotations.
  • Can be combined with the BaseMapper for extra power.
info
  1. For bigger query, split it across multiple lines using a string array.
  2. When building with Java 13+, you can also use Text Blocks to manage bigger query more intuitively.
Define Mapper
@SimpleMapper
public interface UserMapper {
@Execute("create table user_info (id int primary key, name varchar(50))")
void createTable();

// Using positional arguments
@Insert("insert into user_info (id,name) values (?, ?)")
void insertPositional(int id, String name);

// Using named arguments
@Insert("insert into user_info (id,name) values (#{id}, #{name})")
void insertNamed(@Param("id") int id, @Param("name") String name);

// Using Bean property names as named arguments
@Insert("insert into user_info (id,name) values (#{id}, #{name})")
void insertBean(User user);

// Map query results to any type
@Query("select * from user_info")
List<User> listUsers();
}
Create Mapper
// 1. Create Configuration
Configuration config = new Configuration();

// 2. Create Session
Session session = config.newSession(dataSource);
Or
Session session = config.newSession(connection);

// 3. Create declarative API
UserMapper mapper = session.createMapper(UserMapper.class);
Call methods
UserMapper userMapper = ...

userMapper.createTable();

// Using positional arguments
userMapper.insertPositional(1, "Bob");

// Using named arguments
Map<String, Object> queryArg = CollectionUtils.asMap("id", 2, "name", "Alice");
userMapper.insertNamed(queryArg);

// Using Bean property names as named arguments
userMapper.insertBean(new User(3, "David"));

// Map query results to any type
List<User> users = userDAO.listUsers();
details