Skip to main content
Hint

This article is generated by AI translation.

Declarative API

The declarative API defines SQL and return results by creating annotated Java interfaces. SQL and invocation logic are separated, making code structure clearer and SQL maintenance more centralized.

Highlights
  • Interface as DAO: each method maps to one SQL statement, declared via @Insert, @Update, @Delete, @Query, @Execute annotations.
  • Supports positional parameters ? and named parameters #{name} — named parameters work with @Param annotations or Bean properties directly.
  • Supports multi-line SQL: use a string array value={} to split long SQL; Java 13+ can also use Text Blocks.
  • Can be combined with the BaseMapper Interface, mixing annotation methods and generic CRUD in the same interface.
  • Results are automatically mapped to Bean, Map, primitive types, etc., including JOIN queries mapped to DTOs.

Define Interface

Annotate the interface with @SimpleMapper; declare SQL with method annotations
@SimpleMapper
public interface UserMapper {
@Execute("create table user_info (id int primary key, name varchar(50))")
void createTable();

// Positional parameters
@Insert("insert into user_info (id,name) values (?, ?)")
int insertPositional(int id, String name);

// Named parameters + @Param
@Insert("insert into user_info (id,name) values (#{id}, #{name})")
int insertNamed(@Param("id") int id, @Param("name") String name);

// Bean properties as named parameters
@Insert("insert into user_info (id,name) values (#{id}, #{name})")
int insertBean(User user);

// Update
@Update("update user_info set name = #{name}, age = #{age} where id = #{id}")
int updateUserInfo(@Param("id") int id, @Param("name") String name, @Param("age") int age);

// Delete
@Delete("delete from user_info where id = #{id}")
int deleteById(@Param("id") int id);

// Query — return list
@Query("select * from user_info")
List<User> listUsers();

// Query — return single object
@Query("select * from user_info where id = #{id}")
User selectById(@Param("id") int id);

// Multi-line SQL (string array)
@Insert({ "insert into user_info",
"(id, name, age, email, create_time)",
"values",
"(#{id}, #{name}, #{age}, #{email}, #{createTime})" })
int insertUserMultiLine(User user);
}

Create and Use

Create a Mapper proxy via Configuration and Session
// 1. Create Configuration
Configuration config = new Configuration();

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

// 3. Create declarative Mapper
UserMapper mapper = session.createMapper(UserMapper.class);
Call interface methods
// Insert
mapper.insertNamed(1, "Bob");
mapper.insertBean(new User(2, "Alice"));

// Query
User user = mapper.selectById(1);
List<User> users = mapper.listUsers();

// Update and delete
mapper.updateUserInfo(1, "Robert", 30);
mapper.deleteById(2);
For more on the Declarative API, see:
details