本文共 2633 字,大约阅读时间需要 8 分钟。
MyBatis 是一款功能强大的 Java 库,它通过简化 SQL 调用,使开发者能够在 Java 应用中高效地与数据库交互。与传统的 JDBC 体系相比,MyBatis 提供了更加简洁、高效的 API,支持事务管理、缓存机制、动态 SQL 分析等高级功能。
在深入 MyBatis API 之前,了解典型的项目目录结构至关重要。以下是推荐的目录布局:
/my_application/├── bin/├── dev/│ └── lib/│ └── mybatis*.jar├── src/│ └── org/│ └── myapp/│ ├── action/│ ├── data/│ ├── model/│ ├── service/│ ├── view/│ └── properties/├── test/│ └── org/│ └── myapp/│ ├── action/│ ├── data/│ ├── model/│ ├── service/│ └── view/└── web/ └── WEB-INF/ └── web.xml
MyBatis 的核心是 SqlSessionFactory
,它用于创建 SqlSession
实例。以下是获取 SqlSessionFactory
的主要方法:
从 XML 文件加载配置:
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();SqlSessionFactory factory = builder.build(inputStream);
使用 Properties 参数:
Properties props = new Properties();props.put("mybatis.environment", "development");SqlSessionFactory factory = builder.build(inputStream, props);
手动配置 Configuration 对象:
Configuration configuration = new Configuration(environment);configuration.setLazyLoadingEnabled(true);configuration.setEnhancementEnabled(true);configuration.getTypeAliasRegistry().registerAlias(Blog.class);...SqlSessionFactory factory = builder.build(configuration);
SqlSession
是 MyBatis 中执行 SQL 操作的核心接口,提供了丰富的方法来执行 CRUD 操作、管理事务,并通过映射器接口实现复杂的 数据操作。
执行 SQL 语句:
int insert = session.insert("insert into table values(#{name})");
事务控制:
try { session.insert("insert into user values(#{user})"); session.commit();} catch (SqlException e) { session.rollback();}
本地缓存:MyBatis 支持本地缓存,通过 clearCache()
方法清空缓存。
映射器接口:
public interface AuthorMapper { Author selectAuthor(int id); ListselectAuthors(); Map selectAuthorsMap(int id); int insertAuthor(Author author); int updateAuthor(Author author); int deleteAuthor(int id);}
MyBatis 3 提供了基于注解的动态 SQL 构建功能,允许开发者自定义复杂的 SQL 操作。常用的注解包括:
@Param:自定义参数名称。
public User getUserById(@Param("id") Integer userId);
@SelectKey:在插入、更新操作前或后执行序列值获取。
@SelectKey(statement = "call next value for user_seq", keyProperty = "userId", before = true)int insertUser(User user);
@Flush:批量执行缓存的 SQL 语句。
@FlushListvoid flush();
通过以上知识,您已经对 MyBatis Java API 有了全面的了解。接下来,将进一步探索 MyBatis 的映射器配置和高级功能,如 SQL �/extensions 及事务管理。
转载地址:http://jsrrz.baihongyu.com/