or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

active-record.mdannotations.mdcode-generation.mdcore-crud.mdindex.mdpagination.mdplugins.mdquery-building.mdservice-layer.mdspring-boot.md

core-crud.mddocs/

0

# Core CRUD Operations

1

2

MyBatis-Plus provides automatic CRUD operations through the BaseMapper interface, eliminating the need to write basic SQL statements while maintaining full type safety and MyBatis compatibility.

3

4

```java

5

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

6

import org.apache.ibatis.session.ResultHandler;

7

import org.apache.ibatis.annotations.Param;

8

import com.baomidou.mybatisplus.core.conditions.Wrapper;

9

import com.baomidou.mybatisplus.core.metadata.IPage;

10

import java.io.Serializable;

11

import java.util.Collection;

12

import java.util.List;

13

import java.util.Map;

14

```

15

16

## Capabilities

17

18

### BaseMapper Interface

19

20

The core mapper interface providing comprehensive database operations with automatic SQL generation.

21

22

```java { .api }

23

/**

24

* Base mapper interface providing CRUD operations for entity type T

25

* @param <T> Entity type

26

*/

27

public interface BaseMapper<T> {

28

29

/**

30

* Insert a record

31

* @param entity Entity object to insert

32

* @return Number of affected rows

33

*/

34

int insert(T entity);

35

36

/**

37

* Delete by primary key

38

* @param id Primary key value

39

* @return Number of affected rows

40

*/

41

int deleteById(Serializable id);

42

43

/**

44

* Delete by column map conditions

45

* @param columnMap Column conditions map

46

* @return Number of affected rows

47

*/

48

int deleteByMap(@Param("cm") Map<String, Object> columnMap);

49

50

/**

51

* Delete by query wrapper conditions

52

* @param queryWrapper Query conditions wrapper

53

* @return Number of affected rows

54

*/

55

int delete(@Param("ew") Wrapper<T> queryWrapper);

56

57

/**

58

* Delete multiple records by primary keys

59

* @param idList Collection of primary key values

60

* @return Number of affected rows

61

*/

62

int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList);

63

64

/**

65

* Update by primary key

66

* @param entity Entity object with primary key

67

* @return Number of affected rows

68

*/

69

int updateById(@Param("et") T entity);

70

71

/**

72

* Update by conditions

73

* @param entity Entity object with new values

74

* @param updateWrapper Update conditions wrapper

75

* @return Number of affected rows

76

*/

77

int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);

78

79

/**

80

* Select by primary key

81

* @param id Primary key value

82

* @return Entity object or null

83

*/

84

T selectById(Serializable id);

85

86

/**

87

* Select multiple records by primary keys

88

* @param idList Collection of primary key values

89

* @return List of entities

90

*/

91

List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);

92

93

/**

94

* Select by column map conditions

95

* @param columnMap Column conditions map

96

* @return List of entities

97

*/

98

List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);

99

100

/**

101

* Select one record by query wrapper conditions

102

* @param queryWrapper Query conditions wrapper

103

* @return Single entity or null

104

*/

105

T selectOne(@Param("ew") Wrapper<T> queryWrapper);

106

107

/**

108

* Count records by query wrapper conditions

109

* @param queryWrapper Query conditions wrapper

110

* @return Total count

111

*/

112

Long selectCount(@Param("ew") Wrapper<T> queryWrapper);

113

114

/**

115

* Select list by query wrapper conditions

116

* @param queryWrapper Query conditions wrapper

117

* @return List of entities

118

*/

119

List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);

120

121

/**

122

* Select list of maps by query wrapper conditions

123

* @param queryWrapper Query conditions wrapper

124

* @return List of maps representing records

125

*/

126

List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);

127

128

/**

129

* Select list of objects by query wrapper conditions

130

* @param queryWrapper Query conditions wrapper

131

* @return List of objects (typically for single column selection)

132

*/

133

List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper);

134

135

/**

136

* Select paginated records

137

* @param page Pagination parameters

138

* @param queryWrapper Query conditions wrapper

139

* @return Paginated results

140

*/

141

<P extends IPage<T>> P selectPage(P page, @Param("ew") Wrapper<T> queryWrapper);

142

143

/**

144

* Select paginated maps

145

* @param page Pagination parameters

146

* @param queryWrapper Query conditions wrapper

147

* @return Paginated map results

148

*/

149

<P extends IPage<Map<String, Object>>> P selectMapsPage(P page, @Param("ew") Wrapper<T> queryWrapper);

150

151

/**

152

* Check if record exists by query wrapper conditions

153

* @param queryWrapper Query conditions wrapper

154

* @return true if record exists, false otherwise

155

*/

156

boolean exists(@Param("ew") Wrapper<T> queryWrapper);

157

158

/**

159

* Select one record with exception control

160

* @param queryWrapper Query conditions wrapper

161

* @param throwEx Whether to throw exception if multiple records found

162

* @return Single entity or null

163

*/

164

T selectOne(@Param("ew") Wrapper<T> queryWrapper, boolean throwEx);

165

166

/**

167

* Delete by primary key with fill strategy

168

* @param id Primary key value

169

* @param useFill Whether to apply auto-fill for deletion

170

* @return Number of affected rows

171

*/

172

int deleteById(Serializable id, boolean useFill);

173

174

/**

175

* Delete multiple records by primary keys with fill strategy

176

* @param idList Collection of primary key values

177

* @param useFill Whether to apply auto-fill for deletion

178

* @return Number of affected rows

179

*/

180

int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList, boolean useFill);

181

182

/**

183

* Select with result handler for memory-efficient processing

184

* @param queryWrapper Query conditions wrapper

185

* @param handler Result handler for streaming processing

186

*/

187

void selectList(@Param("ew") Wrapper<T> queryWrapper, ResultHandler<T> handler);

188

189

/**

190

* Select batch IDs with result handler

191

* @param idList Collection of primary key values

192

* @param handler Result handler for streaming processing

193

*/

194

void selectBatchIds(@Param("coll") Collection<? extends Serializable> idList, ResultHandler<T> handler);

195

}

196

```

197

198

### Usage Examples

199

200

**Basic Setup:**

201

202

```java

203

// Entity class

204

@TableName("user")

205

public class User {

206

@TableId(type = IdType.AUTO)

207

private Long id;

208

private String name;

209

private Integer age;

210

private String email;

211

212

// constructors, getters, setters...

213

}

214

215

// Mapper interface

216

@Mapper

217

public interface UserMapper extends BaseMapper<User> {

218

// Inherits all BaseMapper methods

219

// Custom methods can be added here

220

}

221

```

222

223

**Insert Operations:**

224

225

```java

226

@Autowired

227

private UserMapper userMapper;

228

229

// Insert single record

230

User user = new User();

231

user.setName("John Doe");

232

user.setAge(25);

233

user.setEmail("john@example.com");

234

235

int result = userMapper.insert(user);

236

// result = 1 if successful

237

// user.getId() will contain the generated ID if using AUTO increment

238

```

239

240

**Delete Operations:**

241

242

```java

243

// Delete by primary key

244

int result = userMapper.deleteById(1L);

245

246

// Delete by conditions map

247

Map<String, Object> conditions = new HashMap<>();

248

conditions.put("age", 25);

249

conditions.put("name", "John");

250

int result = userMapper.deleteByMap(conditions);

251

252

// Delete by query wrapper

253

QueryWrapper<User> wrapper = new QueryWrapper<>();

254

wrapper.eq("age", 25).like("name", "John");

255

int result = userMapper.delete(wrapper);

256

257

// Delete multiple by IDs

258

List<Long> ids = Arrays.asList(1L, 2L, 3L);

259

int result = userMapper.deleteBatchIds(ids);

260

```

261

262

**Update Operations:**

263

264

```java

265

// Update by primary key (only non-null fields are updated)

266

User user = new User();

267

user.setId(1L);

268

user.setAge(26); // Only age will be updated

269

int result = userMapper.updateById(user);

270

271

// Update with conditions

272

User user = new User();

273

user.setAge(26);

274

275

UpdateWrapper<User> wrapper = new UpdateWrapper<>();

276

wrapper.eq("name", "John").lt("age", 30);

277

int result = userMapper.update(user, wrapper);

278

```

279

280

**Select Operations:**

281

282

```java

283

// Select by primary key

284

User user = userMapper.selectById(1L);

285

286

// Select multiple by IDs

287

List<Long> ids = Arrays.asList(1L, 2L, 3L);

288

List<User> users = userMapper.selectBatchIds(ids);

289

290

// Select by conditions map

291

Map<String, Object> conditions = new HashMap<>();

292

conditions.put("age", 25);

293

List<User> users = userMapper.selectByMap(conditions);

294

295

// Select with query wrapper

296

QueryWrapper<User> wrapper = new QueryWrapper<>();

297

wrapper.eq("age", 25).orderByDesc("id").last("LIMIT 10");

298

List<User> users = userMapper.selectList(wrapper);

299

300

// Select one record

301

QueryWrapper<User> wrapper = new QueryWrapper<>();

302

wrapper.eq("email", "john@example.com");

303

User user = userMapper.selectOne(wrapper);

304

305

// Count records

306

QueryWrapper<User> wrapper = new QueryWrapper<>();

307

wrapper.gt("age", 18);

308

Long count = userMapper.selectCount(wrapper);

309

310

// Select as maps

311

QueryWrapper<User> wrapper = new QueryWrapper<>();

312

wrapper.select("name", "age").gt("age", 18);

313

List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);

314

315

// Select objects (for single column)

316

QueryWrapper<User> wrapper = new QueryWrapper<>();

317

wrapper.select("name").gt("age", 18);

318

List<Object> names = userMapper.selectObjs(wrapper);

319

320

// Paginated select

321

Page<User> page = new Page<>(1, 10); // current page, page size

322

QueryWrapper<User> wrapper = new QueryWrapper<>();

323

wrapper.gt("age", 18).orderByDesc("id");

324

IPage<User> userPage = userMapper.selectPage(page, wrapper);

325

326

System.out.println("Total: " + userPage.getTotal());

327

System.out.println("Records: " + userPage.getRecords().size());

328

```

329

330

**Enhanced Operations (MyBatis-Plus 3.5.7+):**

331

332

```java

333

// Check if record exists

334

QueryWrapper<User> wrapper = new QueryWrapper<>();

335

wrapper.eq("email", "john@example.com");

336

boolean exists = userMapper.exists(wrapper);

337

338

// Select one with exception control

339

QueryWrapper<User> wrapper = new QueryWrapper<>();

340

wrapper.like("name", "John");

341

User user = userMapper.selectOne(wrapper, false); // Won't throw exception if multiple found

342

343

// Delete with fill strategy (useful with @TableLogic)

344

int result = userMapper.deleteById(1L, true); // Apply auto-fill for logical deletion

345

346

// Batch delete with fill strategy

347

List<Long> ids = Arrays.asList(1L, 2L, 3L);

348

int result = userMapper.deleteBatchIds(ids, true);

349

350

// Memory-efficient processing with ResultHandler

351

QueryWrapper<User> wrapper = new QueryWrapper<>();

352

wrapper.gt("age", 18);

353

354

userMapper.selectList(wrapper, new ResultHandler<User>() {

355

@Override

356

public void handleResult(ResultContext<? extends User> resultContext) {

357

User user = resultContext.getResultObject();

358

// Process each user individually without loading all into memory

359

processUser(user);

360

}

361

});

362

363

// Stream processing for large batch operations

364

List<Long> largeIdList = getLargeIdList(); // Thousands of IDs

365

userMapper.selectBatchIds(largeIdList, user -> {

366

// Process each user as it's retrieved

367

processUser(user);

368

});

369

```

370

371

### Error Handling

372

373

All BaseMapper methods may throw `MyBatisSystemException` or its subclasses for SQL execution errors. Common scenarios:

374

375

- **Constraint violations**: Foreign key, unique constraints

376

- **Data type mismatches**: Invalid data for column types

377

- **Connection issues**: Database connectivity problems

378

- **Mapping errors**: Entity annotation configuration issues

379

380

```java

381

try {

382

userMapper.insert(user);

383

} catch (MyBatisSystemException e) {

384

// Handle database errors

385

log.error("Failed to insert user", e);

386

throw new ServiceException("User creation failed", e);

387

}

388

```

389

390

### Performance Considerations

391

392

- **Batch operations**: Use `deleteBatchIds()` and `selectBatchIds()` for multiple records

393

- **Selective updates**: `updateById()` only updates non-null fields by default

394

- **Query optimization**: Use `selectMaps()` or `selectObjs()` for partial column selection

395

- **Pagination**: Always use pagination for large result sets

396

- **Indexing**: Ensure proper database indexes for query conditions