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

service-layer.mddocs/

0

# Service Layer

1

2

MyBatis-Plus provides a high-level service layer abstraction with the IService interface and ServiceImpl base class, offering business-logic-focused methods, batch operations, and convenient utilities built on top of BaseMapper functionality.

3

4

## Capabilities

5

6

### IService Interface

7

8

High-level service interface providing comprehensive business operations with batch processing and convenience methods.

9

10

```java { .api }

11

/**

12

* Service interface providing business-logic-focused operations

13

* @param <T> Entity type

14

*/

15

public interface IService<T> {

16

17

// ==================== Save Operations ====================

18

19

/**

20

* Save a single entity

21

* @param entity Entity to save

22

* @return true if successful

23

*/

24

boolean save(T entity);

25

26

/**

27

* Save multiple entities in batch

28

* @param entityList List of entities to save

29

* @return true if all successful

30

*/

31

boolean saveBatch(Collection<T> entityList);

32

33

/**

34

* Save multiple entities in batch with batch size control

35

* @param entityList List of entities to save

36

* @param batchSize Batch size for processing

37

* @return true if all successful

38

*/

39

boolean saveBatch(Collection<T> entityList, int batchSize);

40

41

/**

42

* Save or update entity (insert if not exists, update if exists)

43

* @param entity Entity to save or update

44

* @return true if successful

45

*/

46

boolean saveOrUpdate(T entity);

47

48

/**

49

* Save or update multiple entities in batch

50

* @param entityList List of entities to save or update

51

* @return true if all successful

52

*/

53

boolean saveOrUpdateBatch(Collection<T> entityList);

54

55

/**

56

* Save or update multiple entities in batch with batch size control

57

* @param entityList List of entities to save or update

58

* @param batchSize Batch size for processing

59

* @return true if all successful

60

*/

61

boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);

62

63

// ==================== Remove Operations ====================

64

65

/**

66

* Remove entity by primary key

67

* @param id Primary key value

68

* @return true if successful

69

*/

70

boolean removeById(Serializable id);

71

72

/**

73

* Remove entities by column map conditions

74

* @param columnMap Column conditions map

75

* @return true if successful

76

*/

77

boolean removeByMap(Map<String, Object> columnMap);

78

79

/**

80

* Remove entities by query wrapper conditions

81

* @param queryWrapper Query conditions wrapper

82

* @return true if successful

83

*/

84

boolean remove(Wrapper<T> queryWrapper);

85

86

/**

87

* Remove multiple entities by primary keys

88

* @param idList Collection of primary key values

89

* @return true if successful

90

*/

91

boolean removeByIds(Collection<? extends Serializable> idList);

92

93

// ==================== Update Operations ====================

94

95

/**

96

* Update entity by primary key (non-null fields only)

97

* @param entity Entity with primary key and new values

98

* @return true if successful

99

*/

100

boolean updateById(T entity);

101

102

/**

103

* Update entities by conditions

104

* @param updateWrapper Update conditions wrapper

105

* @return true if successful

106

*/

107

boolean update(Wrapper<T> updateWrapper);

108

109

/**

110

* Update entities with new values by conditions

111

* @param entity Entity with new values

112

* @param updateWrapper Update conditions wrapper

113

* @return true if successful

114

*/

115

boolean update(T entity, Wrapper<T> updateWrapper);

116

117

/**

118

* Update multiple entities by primary keys in batch

119

* @param entityList List of entities with primary keys and new values

120

* @return true if all successful

121

*/

122

boolean updateBatchById(Collection<T> entityList);

123

124

/**

125

* Update multiple entities by primary keys in batch with batch size control

126

* @param entityList List of entities with primary keys and new values

127

* @param batchSize Batch size for processing

128

* @return true if all successful

129

*/

130

boolean updateBatchById(Collection<T> entityList, int batchSize);

131

132

// ==================== Get Operations ====================

133

134

/**

135

* Get entity by primary key

136

* @param id Primary key value

137

* @return Entity or null if not found

138

*/

139

T getById(Serializable id);

140

141

/**

142

* Get entities by primary keys

143

* @param idList Collection of primary key values

144

* @return List of entities

145

*/

146

List<T> listByIds(Collection<? extends Serializable> idList);

147

148

/**

149

* Get entities by column map conditions

150

* @param columnMap Column conditions map

151

* @return List of entities

152

*/

153

List<T> listByMap(Map<String, Object> columnMap);

154

155

/**

156

* Get single entity by query wrapper conditions

157

* @param queryWrapper Query conditions wrapper

158

* @return Single entity or null

159

* @throws TooManyResultsException if more than one result found

160

*/

161

T getOne(Wrapper<T> queryWrapper);

162

163

/**

164

* Get single entity by query wrapper conditions with strict mode control

165

* @param queryWrapper Query conditions wrapper

166

* @param throwEx Whether to throw exception if more than one result

167

* @return Single entity or null

168

*/

169

T getOne(Wrapper<T> queryWrapper, boolean throwEx);

170

171

/**

172

* Get single map by query wrapper conditions

173

* @param queryWrapper Query conditions wrapper

174

* @return Single map or null

175

*/

176

Map<String, Object> getMap(Wrapper<T> queryWrapper);

177

178

/**

179

* Get single object by query wrapper conditions

180

* @param queryWrapper Query conditions wrapper

181

* @param mapper Function to transform the result

182

* @return Transformed object or null

183

*/

184

<V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);

185

186

// ==================== Count Operations ====================

187

188

/**

189

* Count all entities

190

* @return Total count

191

*/

192

long count();

193

194

/**

195

* Count entities by query wrapper conditions

196

* @param queryWrapper Query conditions wrapper

197

* @return Count matching conditions

198

*/

199

long count(Wrapper<T> queryWrapper);

200

201

// ==================== List Operations ====================

202

203

/**

204

* List all entities

205

* @return List of all entities

206

*/

207

List<T> list();

208

209

/**

210

* List entities by query wrapper conditions

211

* @param queryWrapper Query conditions wrapper

212

* @return List of matching entities

213

*/

214

List<T> list(Wrapper<T> queryWrapper);

215

216

/**

217

* Get paginated entities

218

* @param page Pagination parameters

219

* @return Paginated results

220

*/

221

<E extends IPage<T>> E page(E page);

222

223

/**

224

* Get paginated entities by query wrapper conditions

225

* @param page Pagination parameters

226

* @param queryWrapper Query conditions wrapper

227

* @return Paginated results

228

*/

229

<E extends IPage<T>> E page(E page, Wrapper<T> queryWrapper);

230

231

/**

232

* List all entities as maps

233

* @return List of maps representing entities

234

*/

235

List<Map<String, Object>> listMaps();

236

237

/**

238

* List entities as maps by query wrapper conditions

239

* @param queryWrapper Query conditions wrapper

240

* @return List of maps matching conditions

241

*/

242

List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper);

243

244

/**

245

* List all entities as objects (single column selection)

246

* @return List of objects

247

*/

248

List<Object> listObjs();

249

250

/**

251

* List all entities as transformed objects

252

* @param mapper Function to transform each result

253

* @return List of transformed objects

254

*/

255

<V> List<V> listObjs(Function<? super Object, V> mapper);

256

257

/**

258

* List entities as objects by query wrapper conditions

259

* @param queryWrapper Query conditions wrapper

260

* @return List of objects matching conditions

261

*/

262

List<Object> listObjs(Wrapper<T> queryWrapper);

263

264

/**

265

* List entities as transformed objects by query wrapper conditions

266

* @param queryWrapper Query conditions wrapper

267

* @param mapper Function to transform each result

268

* @return List of transformed objects matching conditions

269

*/

270

<V> List<V> listObjs(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);

271

272

/**

273

* Get paginated maps by query wrapper conditions

274

* @param page Pagination parameters

275

* @param queryWrapper Query conditions wrapper

276

* @return Paginated map results

277

*/

278

<E extends IPage<Map<String, Object>>> E pageMaps(E page, Wrapper<T> queryWrapper);

279

280

// ==================== Chain Query Operations ====================

281

282

/**

283

* Create a lambda query chain for fluent querying

284

* @return LambdaQueryChainWrapper instance

285

*/

286

default LambdaQueryChainWrapper<T> lambdaQuery() {

287

return ChainWrappers.lambdaQueryChain(getBaseMapper());

288

}

289

290

/**

291

* Create a lambda update chain for fluent updating

292

* @return LambdaUpdateChainWrapper instance

293

*/

294

default LambdaUpdateChainWrapper<T> lambdaUpdate() {

295

return ChainWrappers.lambdaUpdateChain(getBaseMapper());

296

}

297

298

/**

299

* Create a query chain for fluent querying

300

* @return QueryChainWrapper instance

301

*/

302

default QueryChainWrapper<T> query() {

303

return ChainWrappers.queryChain(getBaseMapper());

304

}

305

306

/**

307

* Create an update chain for fluent updating

308

* @return UpdateChainWrapper instance

309

*/

310

default UpdateChainWrapper<T> update() {

311

return ChainWrappers.updateChain(getBaseMapper());

312

}

313

314

// ==================== Mapper Access ====================

315

316

/**

317

* Get the underlying BaseMapper instance

318

* @return BaseMapper instance

319

*/

320

BaseMapper<T> getBaseMapper();

321

322

/**

323

* Get the entity class

324

* @return Entity class

325

*/

326

Class<T> getEntityClass();

327

}

328

```

329

330

### ServiceImpl Base Class

331

332

Abstract base class implementing IService interface with BaseMapper integration.

333

334

```java { .api }

335

/**

336

* Service implementation base class

337

* @param <M> Mapper type extending BaseMapper

338

* @param <T> Entity type

339

*/

340

public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {

341

342

/**

343

* BaseMapper instance (injected automatically)

344

*/

345

@Autowired

346

protected M baseMapper;

347

348

/**

349

* Logger instance

350

*/

351

protected Log log = LogFactory.getLog(getClass());

352

353

/**

354

* Get the BaseMapper instance

355

* @return BaseMapper instance

356

*/

357

@Override

358

public M getBaseMapper() {

359

return baseMapper;

360

}

361

362

/**

363

* Get the entity class (automatically detected)

364

* @return Entity class

365

*/

366

@Override

367

public Class<T> getEntityClass() {

368

return (Class<T>) ReflectionKit.getSuperClassGenericType(this.getClass(), ServiceImpl.class, 1);

369

}

370

371

// All IService methods are implemented using BaseMapper operations

372

// with appropriate error handling and transaction management

373

}

374

```

375

376

### Db Utility Class (MyBatis-Plus 3.5.7+)

377

378

Static utility class providing direct access to service operations without dependency injection, useful for utility methods and static contexts.

379

380

```java { .api }

381

/**

382

* Static service utility class for database operations

383

*/

384

public final class Db {

385

386

// ==================== Save Operations ====================

387

388

/**

389

* Save a single entity statically

390

* @param entity Entity to save

391

* @return true if successful

392

*/

393

public static <T> boolean save(T entity);

394

395

/**

396

* Save multiple entities in batch statically

397

* @param entityList List of entities to save

398

* @return true if all successful

399

*/

400

public static <T> boolean saveBatch(Collection<T> entityList);

401

402

/**

403

* Save multiple entities in batch with batch size control

404

* @param entityList List of entities to save

405

* @param batchSize Batch size for processing

406

* @return true if all successful

407

*/

408

public static <T> boolean saveBatch(Collection<T> entityList, int batchSize);

409

410

/**

411

* Save or update entity statically

412

* @param entity Entity to save or update

413

* @return true if successful

414

*/

415

public static <T> boolean saveOrUpdate(T entity);

416

417

/**

418

* Save or update multiple entities in batch statically

419

* @param entityList List of entities to save or update

420

* @return true if all successful

421

*/

422

public static <T> boolean saveOrUpdateBatch(Collection<T> entityList);

423

424

// ==================== Remove Operations ====================

425

426

/**

427

* Remove entity by primary key statically

428

* @param entity Entity with ID to remove (or just ID value)

429

* @return true if successful

430

*/

431

public static <T> boolean removeById(T entity);

432

433

/**

434

* Remove entity by primary key value statically

435

* @param id Primary key value

436

* @param entityClass Entity class

437

* @return true if successful

438

*/

439

public static <T> boolean removeById(Serializable id, Class<T> entityClass);

440

441

/**

442

* Remove multiple entities by primary keys statically

443

* @param idList Collection of primary key values

444

* @param entityClass Entity class

445

* @return true if successful

446

*/

447

public static <T> boolean removeByIds(Collection<? extends Serializable> idList, Class<T> entityClass);

448

449

// ==================== Update Operations ====================

450

451

/**

452

* Update entity by primary key statically

453

* @param entity Entity with primary key and new values

454

* @return true if successful

455

*/

456

public static <T> boolean updateById(T entity);

457

458

/**

459

* Update multiple entities by primary keys statically

460

* @param entityList List of entities with primary keys and new values

461

* @return true if all successful

462

*/

463

public static <T> boolean updateBatchById(Collection<T> entityList);

464

465

// ==================== Query Operations ====================

466

467

/**

468

* Get entity by primary key statically

469

* @param id Primary key value

470

* @param entityClass Entity class

471

* @return Entity or null if not found

472

*/

473

public static <T> T getById(Serializable id, Class<T> entityClass);

474

475

/**

476

* Get multiple entities by primary keys statically

477

* @param idList Collection of primary key values

478

* @param entityClass Entity class

479

* @return List of entities

480

*/

481

public static <T> List<T> listByIds(Collection<? extends Serializable> idList, Class<T> entityClass);

482

483

/**

484

* List all entities statically

485

* @param entityClass Entity class

486

* @return List of all entities

487

*/

488

public static <T> List<T> list(Class<T> entityClass);

489

490

/**

491

* List entities by query wrapper statically

492

* @param queryWrapper Query conditions wrapper

493

* @param entityClass Entity class

494

* @return List of matching entities

495

*/

496

public static <T> List<T> list(Wrapper<T> queryWrapper, Class<T> entityClass);

497

498

/**

499

* Count entities statically

500

* @param entityClass Entity class

501

* @return Total count

502

*/

503

public static <T> long count(Class<T> entityClass);

504

505

/**

506

* Count entities by query wrapper statically

507

* @param queryWrapper Query conditions wrapper

508

* @param entityClass Entity class

509

* @return Count of matching entities

510

*/

511

public static <T> long count(Wrapper<T> queryWrapper, Class<T> entityClass);

512

513

/**

514

* Get paginated entities statically

515

* @param page Pagination parameters

516

* @param entityClass Entity class

517

* @return Paginated results

518

*/

519

public static <T> IPage<T> page(IPage<T> page, Class<T> entityClass);

520

521

/**

522

* Get paginated entities by query wrapper statically

523

* @param page Pagination parameters

524

* @param queryWrapper Query conditions wrapper

525

* @param entityClass Entity class

526

* @return Paginated results

527

*/

528

public static <T> IPage<T> page(IPage<T> page, Wrapper<T> queryWrapper, Class<T> entityClass);

529

530

// ==================== Chain Operations ====================

531

532

/**

533

* Create lambda query chain statically

534

* @param entityClass Entity class

535

* @return LambdaQueryChainWrapper instance

536

*/

537

public static <T> LambdaQueryChainWrapper<T> lambdaQuery(Class<T> entityClass);

538

539

/**

540

* Create lambda update chain statically

541

* @param entityClass Entity class

542

* @return LambdaUpdateChainWrapper instance

543

*/

544

public static <T> LambdaUpdateChainWrapper<T> lambdaUpdate(Class<T> entityClass);

545

}

546

```

547

548

## Usage Examples

549

550

**Basic Service Setup:**

551

552

```java

553

// Entity class

554

@TableName("user")

555

public class User {

556

@TableId(type = IdType.AUTO)

557

private Long id;

558

private String name;

559

private Integer age;

560

private String email;

561

private LocalDateTime createTime;

562

563

// constructors, getters, setters...

564

}

565

566

// Mapper interface

567

public interface UserMapper extends BaseMapper<User> {

568

}

569

570

// Service interface

571

public interface UserService extends IService<User> {

572

// Custom business methods can be added here

573

}

574

575

// Service implementation

576

@Service

577

public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

578

}

579

```

580

581

**Save Operations:**

582

583

```java

584

@Autowired

585

private UserService userService;

586

587

// Save single entity

588

User user = new User();

589

user.setName("John Doe");

590

user.setAge(25);

591

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

592

593

boolean success = userService.save(user);

594

// user.getId() will contain the generated ID

595

596

// Save multiple entities

597

List<User> users = Arrays.asList(

598

new User("Alice", 22, "alice@example.com"),

599

new User("Bob", 28, "bob@example.com"),

600

new User("Charlie", 35, "charlie@example.com")

601

);

602

603

boolean success = userService.saveBatch(users);

604

605

// Save with batch size control (for large datasets)

606

boolean success = userService.saveBatch(users, 100);

607

608

// Save or update (insert if new, update if exists)

609

User user = new User();

610

user.setId(1L); // If ID exists, it will update; otherwise insert

611

user.setName("Updated Name");

612

user.setAge(26);

613

614

boolean success = userService.saveOrUpdate(user);

615

616

// Batch save or update

617

List<User> users = getUsers(); // Mix of new and existing users

618

boolean success = userService.saveOrUpdateBatch(users);

619

```

620

621

**Remove Operations:**

622

623

```java

624

// Remove by ID

625

boolean success = userService.removeById(1L);

626

627

// Remove by conditions map

628

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

629

conditions.put("age", 25);

630

conditions.put("status", 0);

631

boolean success = userService.removeByMap(conditions);

632

633

// Remove by query wrapper

634

boolean success = userService.remove(

635

Wrappers.<User>lambdaQuery()

636

.eq(User::getAge, 25)

637

.like(User::getName, "test")

638

);

639

640

// Remove multiple by IDs

641

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

642

boolean success = userService.removeByIds(ids);

643

```

644

645

**Update Operations:**

646

647

```java

648

// Update by ID (only non-null fields)

649

User user = new User();

650

user.setId(1L);

651

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

652

boolean success = userService.updateById(user);

653

654

// Update by conditions

655

boolean success = userService.update(

656

Wrappers.<User>lambdaUpdate()

657

.set(User::getStatus, 1)

658

.set(User::getUpdateTime, LocalDateTime.now())

659

.eq(User::getAge, 25)

660

);

661

662

// Update with entity and conditions

663

User updateUser = new User();

664

updateUser.setStatus(1);

665

666

boolean success = userService.update(updateUser,

667

Wrappers.<User>lambdaQuery()

668

.eq(User::getDeptId, 10)

669

.gt(User::getAge, 18)

670

);

671

672

// Batch update by IDs

673

List<User> users = getUsersToUpdate();

674

boolean success = userService.updateBatchById(users);

675

676

// Batch update with batch size control

677

boolean success = userService.updateBatchById(users, 50);

678

```

679

680

**Query Operations:**

681

682

```java

683

// Get by ID

684

User user = userService.getById(1L);

685

686

// Get multiple by IDs

687

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

688

List<User> users = userService.listByIds(ids);

689

690

// Get by conditions map

691

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

692

conditions.put("age", 25);

693

conditions.put("status", 1);

694

List<User> users = userService.listByMap(conditions);

695

696

// Get one by conditions (throws exception if multiple results)

697

User user = userService.getOne(

698

Wrappers.<User>lambdaQuery()

699

.eq(User::getEmail, "john@example.com")

700

);

701

702

// Get one without exception (returns first if multiple)

703

User user = userService.getOne(

704

Wrappers.<User>lambdaQuery()

705

.eq(User::getAge, 25), false

706

);

707

708

// Count operations

709

long totalUsers = userService.count();

710

711

long activeUsers = userService.count(

712

Wrappers.<User>lambdaQuery()

713

.eq(User::getStatus, 1)

714

);

715

716

// List operations

717

List<User> allUsers = userService.list();

718

719

List<User> activeUsers = userService.list(

720

Wrappers.<User>lambdaQuery()

721

.eq(User::getStatus, 1)

722

.orderByDesc(User::getCreateTime)

723

);

724

725

// Pagination

726

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

727

IPage<User> userPage = userService.page(page,

728

Wrappers.<User>lambdaQuery()

729

.eq(User::getStatus, 1)

730

.orderByDesc(User::getCreateTime)

731

);

732

733

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

734

System.out.println("Pages: " + userPage.getPages());

735

System.out.println("Current: " + userPage.getCurrent());

736

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

737

738

// List as maps

739

List<Map<String, Object>> userMaps = userService.listMaps(

740

Wrappers.<User>lambdaQuery()

741

.select(User::getId, User::getName, User::getEmail)

742

.eq(User::getStatus, 1)

743

);

744

745

// List as objects (single column)

746

List<Object> names = userService.listObjs(

747

Wrappers.<User>lambdaQuery()

748

.select(User::getName)

749

.eq(User::getStatus, 1)

750

);

751

752

// List as transformed objects

753

List<String> upperNames = userService.listObjs(

754

Wrappers.<User>lambdaQuery()

755

.select(User::getName)

756

.eq(User::getStatus, 1),

757

obj -> obj.toString().toUpperCase()

758

);

759

```

760

761

**Chain Query Operations:**

762

763

```java

764

// Lambda query chain

765

List<User> users = userService.lambdaQuery()

766

.eq(User::getStatus, 1)

767

.gt(User::getAge, 18)

768

.orderByDesc(User::getCreateTime)

769

.list();

770

771

User user = userService.lambdaQuery()

772

.eq(User::getEmail, "john@example.com")

773

.one();

774

775

long count = userService.lambdaQuery()

776

.eq(User::getStatus, 1)

777

.count();

778

779

// Lambda update chain

780

boolean success = userService.lambdaUpdate()

781

.set(User::getStatus, 0)

782

.set(User::getUpdateTime, LocalDateTime.now())

783

.eq(User::getId, 1L)

784

.update();

785

786

// Query chain (string-based)

787

List<User> users = userService.query()

788

.eq("status", 1)

789

.gt("age", 18)

790

.orderByDesc("create_time")

791

.list();

792

793

// Update chain (string-based)

794

boolean success = userService.update()

795

.set("status", 0)

796

.set("update_time", LocalDateTime.now())

797

.eq("id", 1L)

798

.update();

799

```

800

801

**Custom Service Methods:**

802

803

```java

804

@Service

805

public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

806

807

@Override

808

public List<User> findActiveUsersByDepartment(Long deptId) {

809

return this.lambdaQuery()

810

.eq(User::getDeptId, deptId)

811

.eq(User::getStatus, 1)

812

.orderByDesc(User::getCreateTime)

813

.list();

814

}

815

816

@Override

817

@Transactional

818

public boolean batchUpdateUserStatus(List<Long> userIds, Integer status) {

819

return this.lambdaUpdate()

820

.set(User::getStatus, status)

821

.set(User::getUpdateTime, LocalDateTime.now())

822

.in(User::getId, userIds)

823

.update();

824

}

825

826

@Override

827

public IPage<User> findUsersByCondition(UserQueryRequest request) {

828

LambdaQueryWrapper<User> wrapper = this.lambdaQuery()

829

.like(StringUtils.isNotBlank(request.getName()), User::getName, request.getName())

830

.eq(request.getStatus() != null, User::getStatus, request.getStatus())

831

.ge(request.getMinAge() != null, User::getAge, request.getMinAge())

832

.le(request.getMaxAge() != null, User::getAge, request.getMaxAge())

833

.orderByDesc(User::getCreateTime)

834

.getWrapper();

835

836

return this.page(new Page<>(request.getCurrent(), request.getSize()), wrapper);

837

}

838

}

839

```

840

841

**Static Db Utility Usage (MyBatis-Plus 3.5.7+):**

842

843

```java

844

import com.baomidou.mybatisplus.extension.toolkit.Db;

845

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

846

847

// Save operations without service injection

848

User user = new User("John", 25, "john@example.com");

849

boolean success = Db.save(user);

850

851

// Batch save

852

List<User> users = Arrays.asList(

853

new User("Alice", 22, "alice@example.com"),

854

new User("Bob", 28, "bob@example.com")

855

);

856

boolean success = Db.saveBatch(users);

857

858

// Save or update

859

User existingUser = Db.getById(1L, User.class);

860

if (existingUser != null) {

861

existingUser.setAge(26);

862

Db.saveOrUpdate(existingUser);

863

}

864

865

// Query operations

866

User user = Db.getById(1L, User.class);

867

List<User> users = Db.listByIds(Arrays.asList(1L, 2L, 3L), User.class);

868

List<User> allUsers = Db.list(User.class);

869

870

// Query with conditions

871

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

872

wrapper.eq(User::getStatus, 1).gt(User::getAge, 18);

873

List<User> activeAdults = Db.list(wrapper, User.class);

874

875

// Count operations

876

long totalUsers = Db.count(User.class);

877

long activeUsers = Db.count(

878

new LambdaQueryWrapper<User>().eq(User::getStatus, 1),

879

User.class

880

);

881

882

// Update operations

883

User user = new User();

884

user.setId(1L);

885

user.setAge(26);

886

boolean success = Db.updateById(user);

887

888

// Remove operations

889

boolean success = Db.removeById(1L, User.class);

890

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

891

boolean success = Db.removeByIds(ids, User.class);

892

893

// Pagination

894

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

895

IPage<User> result = Db.page(page, User.class);

896

897

// Chain operations with static access

898

List<User> users = Db.lambdaQuery(User.class)

899

.eq(User::getStatus, 1)

900

.gt(User::getAge, 18)

901

.orderByDesc(User::getCreateTime)

902

.list();

903

904

boolean updateSuccess = Db.lambdaUpdate(User.class)

905

.set(User::getStatus, 0)

906

.eq(User::getId, 1L)

907

.update();

908

909

// Useful in utility classes or static methods

910

public class UserUtils {

911

912

public static List<User> getActiveUsersByDepartment(Long deptId) {

913

return Db.lambdaQuery(User.class)

914

.eq(User::getDeptId, deptId)

915

.eq(User::getStatus, 1)

916

.list();

917

}

918

919

public static boolean deactivateExpiredUsers() {

920

return Db.lambdaUpdate(User.class)

921

.set(User::getStatus, 0)

922

.lt(User::getExpireTime, LocalDateTime.now())

923

.update();

924

}

925

}

926

```

927

928

**Error Handling:**

929

930

```java

931

try {

932

boolean success = userService.save(user);

933

if (!success) {

934

throw new BusinessException("Failed to save user");

935

}

936

} catch (DuplicateKeyException e) {

937

throw new BusinessException("User email already exists", e);

938

} catch (DataIntegrityViolationException e) {

939

throw new BusinessException("Data integrity violation", e);

940

}

941

942

// Using getOne with exception control

943

try {

944

User user = userService.getOne(

945

Wrappers.<User>lambdaQuery().eq(User::getEmail, email)

946

);

947

} catch (TooManyResultsException e) {

948

throw new BusinessException("Multiple users found with same email", e);

949

}

950

```

951

952

**Performance Considerations:**

953

954

- Use batch operations (`saveBatch`, `updateBatchById`) for multiple records

955

- Control batch size for large datasets to avoid memory issues

956

- Use `count()` instead of `list().size()` for counting

957

- Select only required columns using `select()` methods

958

- Use pagination for large result sets

959

- Consider database transactions for consistency

960

- Use `getOne(wrapper, false)` to avoid exceptions when multiple results expected