7. Best Practices & FAQ
6.1 Transaction Management
mybatis-dynamic integrates seamlessly with Spring's transaction management.
- Usage: Simply add
@Transactionalto your Service methods. - Mechanism: The framework's
DataManagerobtains theSqlSessionfrom Spring'sSqlSessionUtils, ensuring it participates in the current active transaction (propagation, rollback, etc.).
@Service
public class UserService extends BaseService<Integer, User> {
@Transactional(rollbackFor = Exception.class)
public void createUserWithProfile(User user, Profile profile) {
this.insert(user); // Uses Transaction A
profileService.insert(profile); // Uses Transaction A
// If query fails here, both inserts roll back.
}
}
6.2 Thread Safety
BaseService/BaseDao: These are singletons in Spring (Scope: Singleton). They are thread-safe because they do not hold conversational state.DataManager: The default implementation is designed to be lightweight. When accessed viaBaseService, it ensures the underlyingSqlSessionis thread-bound (viaThreadLocalin Spring).- Chains (
QueryChain, etc.): These are NOT thread-safe. They are stateful objects created per request. - Correct: Create, configure, and execute in one method scope.
- Incorrect: Storing a
QueryChaininstance in a class field and reusing it across threads.
6.3 Performance Tips
- Select What You Need: Use
.queryChain().select(...)rather than fetchingSELECT *, especially if tables have huge text columns. - Batch Operations: Always use
.batchInsert()or.batchUpdate()for lists > 50 items. - Indices: Use the
@BasicField(ddlIndex = true)annotation to ensure yourwhereclauses are backed by DB indices. The framework handles index creation for you.