or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cache-system.mdindex.mdmapping-annotations.mdplugin-system.mdsession-management.mdtransaction-management.mdtype-handling.md

index.mddocs/

0

# MyBatis

1

2

MyBatis is a Java SQL mapping framework that eliminates almost all of the JDBC code and manual setting of parameters and retrieval of results. It uses XML descriptors or annotations to configure and map primitives, Map interfaces, and Java POJOs to database records.

3

4

## Package Information

5

6

- **Package Name**: org.mybatis:mybatis

7

- **Package Type**: maven

8

- **Language**: Java

9

- **Installation**: Add to `pom.xml`:

10

```xml

11

<dependency>

12

<groupId>org.mybatis</groupId>

13

<artifactId>mybatis</artifactId>

14

<version>3.6.0</version>

15

</dependency>

16

```

17

18

## Core Imports

19

20

```java

21

import org.apache.ibatis.session.SqlSession;

22

import org.apache.ibatis.session.SqlSessionFactory;

23

import org.apache.ibatis.session.SqlSessionFactoryBuilder;

24

import org.apache.ibatis.io.Resources;

25

```

26

27

For annotation-based mappers:

28

29

```java

30

import org.apache.ibatis.annotations.Select;

31

import org.apache.ibatis.annotations.Insert;

32

import org.apache.ibatis.annotations.Update;

33

import org.apache.ibatis.annotations.Delete;

34

import org.apache.ibatis.annotations.Param;

35

```

36

37

## Basic Usage

38

39

```java

40

import org.apache.ibatis.session.SqlSession;

41

import org.apache.ibatis.session.SqlSessionFactory;

42

import org.apache.ibatis.session.SqlSessionFactoryBuilder;

43

import org.apache.ibatis.io.Resources;

44

45

// 1. Create SqlSessionFactory from XML configuration

46

InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");

47

SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

48

49

// 2. Open a session and execute SQL

50

try (SqlSession session = sqlSessionFactory.openSession()) {

51

// Using statement ID with parameter

52

User user = session.selectOne("selectUser", 1);

53

54

// Using mapper interface (type-safe)

55

UserMapper mapper = session.getMapper(UserMapper.class);

56

List<User> users = mapper.findAll();

57

58

// Commit changes

59

session.commit();

60

}

61

```

62

63

## Architecture

64

65

MyBatis is built around several key components:

66

67

- **SqlSessionFactory**: Factory for creating database sessions, typically configured once per application

68

- **SqlSession**: Primary interface for executing SQL statements and managing transactions

69

- **Mapper Interfaces**: Type-safe interfaces that MyBatis implements dynamically using proxies

70

- **Configuration**: Central configuration object containing all settings, type handlers, and statement mappings

71

- **Type Handlers**: Convert between Java types and JDBC types during parameter setting and result retrieval

72

- **Cache System**: Two-level caching with session-level (L1) and global (L2) cache support

73

- **Dynamic SQL**: XML-based templating system for building conditional SQL statements

74

75

## Capabilities

76

77

### Session Management

78

79

Core session and transaction management functionality. SqlSession is the primary interface for all database operations.

80

81

```java { .api }

82

// Factory for creating sessions

83

interface SqlSessionFactory {

84

SqlSession openSession();

85

SqlSession openSession(boolean autoCommit);

86

SqlSession openSession(ExecutorType execType);

87

Configuration getConfiguration();

88

}

89

90

// Primary database session interface

91

interface SqlSession extends Closeable {

92

<T> T selectOne(String statement, Object parameter);

93

<T> List<T> selectList(String statement, Object parameter);

94

int insert(String statement, Object parameter);

95

int update(String statement, Object parameter);

96

int delete(String statement, Object parameter);

97

void commit();

98

void rollback();

99

<T> T getMapper(Class<T> type);

100

void close();

101

}

102

```

103

104

[Session Management](./session-management.md)

105

106

### Mapping Annotations

107

108

Annotation-based SQL mapping for declarative database operations. Provides type-safe alternatives to XML configuration.

109

110

```java { .api }

111

// Core SQL operation annotations

112

@interface Select {

113

String[] value();

114

}

115

116

@interface Insert {

117

String[] value();

118

}

119

120

@interface Update {

121

String[] value();

122

}

123

124

@interface Delete {

125

String[] value();

126

}

127

128

// Parameter and result mapping

129

@interface Param {

130

String value();

131

}

132

133

@interface Results {

134

String id() default "";

135

Result[] value();

136

}

137

138

@interface Result {

139

String column();

140

String property();

141

Class<?> javaType() default void.class;

142

JdbcType jdbcType() default JdbcType.UNDEFINED;

143

}

144

```

145

146

[Mapping Annotations](./mapping-annotations.md)

147

148

### Type Handling

149

150

Comprehensive type conversion system between Java types and JDBC types, with extensive built-in support and custom type handler capabilities.

151

152

```java { .api }

153

// Core type handler interface

154

interface TypeHandler<T> {

155

void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;

156

T getResult(ResultSet rs, String columnName) throws SQLException;

157

T getResult(ResultSet rs, int columnIndex) throws SQLException;

158

T getResult(CallableStatement cs, int columnIndex) throws SQLException;

159

}

160

161

// Base implementation for custom handlers

162

abstract class BaseTypeHandler<T> implements TypeHandler<T> {

163

public abstract void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;

164

public abstract T getNullableResult(ResultSet rs, String columnName) throws SQLException;

165

public abstract T getNullableResult(ResultSet rs, int columnIndex) throws SQLException;

166

public abstract T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException;

167

}

168

```

169

170

[Type Handling](./type-handling.md)

171

172

### Cache System

173

174

Multi-level caching system with configurable eviction policies and decorators for performance optimization.

175

176

```java { .api }

177

// Core cache interface

178

interface Cache {

179

String getId();

180

void putObject(Object key, Object value);

181

Object getObject(Object key);

182

Object removeObject(Object key);

183

void clear();

184

int getSize();

185

}

186

187

// Cache configuration annotation

188

@interface CacheNamespace {

189

Class<? extends Cache> implementation() default PerpetualCache.class;

190

Class<? extends Cache> eviction() default LruCache.class;

191

long flushInterval() default 0;

192

int size() default 1024;

193

boolean readWrite() default true;

194

boolean blocking() default false;

195

}

196

```

197

198

[Cache System](./cache-system.md)

199

200

### Transaction Management

201

202

Clean abstraction over JDBC and managed transactions with support for different transaction factories.

203

204

```java { .api }

205

// Core transaction interface

206

interface Transaction {

207

Connection getConnection() throws SQLException;

208

void commit() throws SQLException;

209

void rollback() throws SQLException;

210

void close() throws SQLException;

211

}

212

213

// Transaction factory interface

214

interface TransactionFactory {

215

void setProperties(Properties props);

216

Transaction newTransaction(Connection conn);

217

Transaction newTransaction(DataSource dataSource, TransactionIsolationLevel level, boolean autoCommit);

218

}

219

220

enum TransactionIsolationLevel {

221

NONE, READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE

222

}

223

```

224

225

[Transaction Management](./transaction-management.md)

226

227

### Plugin System

228

229

Interceptor-based plugin system for AOP-style cross-cutting concerns like logging, performance monitoring, and custom behavior injection.

230

231

```java { .api }

232

// Core plugin interface

233

interface Interceptor {

234

Object intercept(Invocation invocation) throws Throwable;

235

default Object plugin(Object target) { return Plugin.wrap(target, this); }

236

default void setProperties(Properties properties) {}

237

}

238

239

// Plugin configuration annotations

240

@interface Intercepts {

241

Signature[] value();

242

}

243

244

@interface Signature {

245

Class<?> type();

246

String method();

247

Class<?>[] args();

248

}

249

```

250

251

[Plugin System](./plugin-system.md)

252

253

## Core Types

254

255

```java { .api }

256

// Execution types

257

enum ExecutorType {

258

SIMPLE, // Basic statement execution

259

REUSE, // PreparedStatement reuse

260

BATCH // Batch operations

261

}

262

263

// JDBC type enumeration

264

enum JdbcType {

265

VARCHAR, INTEGER, TIMESTAMP, BOOLEAN, BIGINT, DECIMAL, DATE, TIME, BLOB, CLOB, ARRAY

266

// ... and all other standard JDBC types

267

}

268

269

// Auto-mapping behavior

270

enum AutoMappingBehavior {

271

NONE, // No auto mapping

272

PARTIAL, // Partial auto mapping

273

FULL // Full auto mapping

274

}

275

276

// Local cache scope

277

enum LocalCacheScope {

278

SESSION, // Session-scoped caching

279

STATEMENT // Statement-scoped caching

280

}

281

282

// Configuration class containing all MyBatis settings

283

class Configuration {

284

public Environment getEnvironment();

285

public void setEnvironment(Environment environment);

286

public boolean isSafeRowBoundsEnabled();

287

public boolean isMapUnderscoreToCamelCase();

288

public boolean isCacheEnabled();

289

public ExecutorType getDefaultExecutorType();

290

public AutoMappingBehavior getAutoMappingBehavior();

291

public LocalCacheScope getLocalCacheScope();

292

public JdbcType getJdbcTypeForNull();

293

// ... many other configuration properties

294

}

295

```