Hint
This article is generated by AI translation.
BaseMapper Interface
The generic BaseMapper interface provides a set of predefined database operations that work with Object Mapping metadata to perform CRUD — no SQL required.
Highlights
- Zero-SQL development: just define entity mappings to get a full set of CRUD methods —
insert,update,delete,selectById, etc. - Built-in sample query
listBySample: pass an entity object and non-null properties automatically become equality conditions. - Built-in paginated query
pageBySample: auto-calculates total records and total pages. - Built-in batch operations:
selectByIdsfor batch primary-key lookup,insert(List)for batch insert. - Switch to the Fluent API via
mapper.query()for complex conditional queries. - Can be combined with the Declarative API — mix predefined methods and custom SQL in the same interface.
Declare Entity Class
Establish mapping with @Table and @Column annotations
@Table("users")
public class User {
@Column(name = "id", primary = true, keyType = KeyTypeEnum.Auto)
private Long id;
@Column("name")
private String name;
@Column("age")
private Integer age;
@Column("email")
private String email;
...
}
Create BaseMapper
Create via Session
Configuration config = new Configuration();
Session session = config.newSession(dataSource);
BaseMapper<User> mapper = session.createBaseMapper(User.class);
CRUD
Basic CRUD operations
// Insert one row
User user = ...
int result = mapper.insert(user);
// Insert multiple rows
int result = mapper.insert(Arrays.asList(user1, user2));
// Query by primary key
User loaded = mapper.selectById(1);
// Batch primary key query
List<User> users = mapper.selectByIds(Arrays.asList(1, 2, 3));
// Update by primary key
user.setAge(30);
int result = mapper.update(user);
// Delete by primary key
int result = mapper.deleteById(1);
Sample Query and Pagination
Conditional queries and pagination via sample object
// Sample query: non-null properties become equality conditions
User sample = new User();
sample.setAge(30);
List<User> result = mapper.listBySample(sample);
// Count query
int count = mapper.countBySample(sample);
// Paginated query
Page pageInfo = mapper.pageInitBySample(sample, 0, 20); // page number starts at 0
PageResult<User> result = mapper.pageBySample(sample, pageInfo);
Switch to Fluent API
Get a builder directly for complex conditions
List<User> result = mapper.query()
.like(User::getName, "A%")
.ge(User::getAge, 20)
.queryForList();
For more details, see: