Java API
SqlSessionFactoryBuilder
SqlSessionFactory build(Reader reader)
SqlSessionFactory build(Reader reader, String environment)
SqlSessionFactory build(Reader reader, Properties properties)
SqlSessionFactory build(Reader reader, String env, Properties props)
SqlSessionFactory build(Configuration config)
String resource = "org/apache/ibatis/builder/MapperConfig.xml";Reader reader = Resources.getResourceAsReader(resource);这里我们用到了Reader接口,在org.apache.ibatis.io包下,其主要接口为:
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(reader);
URL getResourceURL(String resource)刚才提到最后一种build方法参数是Configation,具体可以这样使用:
URL getResourceURL(ClassLoader loader, String resource)
InputStream getResourceAsStream(String resource)
InputStream getResourceAsStream(ClassLoader loader, String resource)
Properties getResourceAsProperties(String resource)
Properties getResourceAsProperties(ClassLoader loader, String resource)
Reader getResourceAsReader(String resource)
Reader getResourceAsReader(ClassLoader loader, String resource)
File getResourceAsFile(String resource)
File getResourceAsFile(ClassLoader loader, String resource)
InputStream getUrlAsStream(String urlString)
Reader getUrlAsReader(String urlString)
Properties getUrlAsProperties(String urlString)
Class classForName(String className)
DataSource dataSource = BaseDataTest.createBlogDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment =
new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.setLazyLoadingEnabled(true);
configuration.setEnhancementEnabled(true);
configuration.getTypeAliasRegistry().registerAlias(Blog.class);
configuration.getTypeAliasRegistry().registerAlias(Post.class);
configuration.getTypeAliasRegistry().registerAlias(Author.class);
configuration.addMapper(BoundBlogMapper.class);
configuration.addMapper(BoundAuthorMapper.class);
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(configuration);
SqlSessionFactory
主要配置一下三个属性
Transaction:是否将事务的范围定义为session,或者auto-commit。
Connection:是否让ibatis从datasource配置中获取连接,还是自己提供数据库连接。
Execution:是否重用PerparedStatement 和 批量操作
SqlSession openSession()默认的openSession()方法不带参数,将会默认启动以下配置:
SqlSession openSession(boolean autoCommit)
SqlSession openSession(Connection connection)
SqlSession openSession(ExecutorType execType)
SqlSession openSession(ExecutorType execType, boolean autoCommit)
SqlSession openSession(ExecutorType execType, Connection connection)
Configuration getConfiguration();
启动事务(Not auto commit)
根据DataSource配置产生数据库连接Connection对象
不重用PreparedStatements 不启用批量操作
autoCommit 和 connection参数并不陌生,execType参数有如下三个值
ExecutorType.SIMPLE 为每条语句的执行创建一个PreparedStatement对象
ExecutorType.REUSE 重用PreparedStatement对象
ExecutorType.BATCH 批量执行
SqlSession
1、Statement Execution Methods
Object selectOne(String statement)
List selectList(String statement)
int insert(String statement)
int update(String statement)
int delete(String statement)
Object selectOne(String statement, Object parameter)
List selectList(String statement, Object parameter)
int insert(String statement, Object parameter)
int update(String statement, Object parameter)
int delete(String statement, Object parameter)
List selectListselectOne和selectList的区别在于selectOne只能返回一个结果,而在返回多个结果或者返回null时抛出异常
(String statement, Object parameter, RowBounds rowBounds)
void select
(String statement, Object parameter, ResultHandler handler)
void select
(String statement, Object parameter, RowBounds rowBounds,
ResultHandler handler)
RwoBounds可以这样使用:
int offset = 100;
int limit = 25;
RowBounds rowBounds = new RowBounds(offset, limit);
ResultHandler可以*控制数据集的每一行数据,需要继承以下接口
package org.apache.ibatis.executor.result;
public interface ResultHandler {
void handleResult(ResultContext context);
}
Transaction Control Methods
void commit()如果设置了auto commit那么这四个方法将没有效果
void commit(boolean force)
void rollback()
void rollback(boolean force)
一般情况下不用使用rollback,ibatis会在没有调用commit的情况下自动rollback,不过还是rollback写一下的好,毕竟习惯了
保证session关闭
SqlSession session = sqlSessionFactory.openSession();
try {
// following 3 lines pseudocod for “doing some work”
session.insert(…);
session.update(…);
session.delete(…);
session.commit();
} finally {
session.close();
}
Using Mappers
接口:
使用:
public class AuthorMapper {
// (Author) selectOne(“selectAuthor”,5);
Author selectAuthor(int id);
// (List
List
// insert(“insertAuthor”, author)
void insertAuthor(Author author);
// updateAuthor(“updateAuhor”, author)
void updateAuthor(Author author);
// delete(“deleteAuthor”,5)
void deleteAuthor(
int id);
}
Mapper Annotations
不喜欢使用annotations进行配置,简略列一下表格:Annotation | Target | XML Equivalent |
@CacheNamespace | Class |
|
@CacheNamespaceRef | Class |
|
@ConstructorArgs | Method |
|
@Arg | Method |
|
@TypeDiscriminator | Method |
|
@Case | Method |
|
@Results | Method |
|
@Result | Method |
|
@One | Method |
|
@Many | Method |
|
@Options | Method | Attribuates of mapped statements |
@Insert @Update @Delete @Select |
Method |
|
@InsertProvider @UpdateProvider @DeleteProvider @SelectProvider |
Method |
|
@Param | Parameter | N/A |
SelectBuilder
在java代码中创建sql语句,可以使用SelectBuilder来辅助:
public String selectBlogsSql() {
BEGIN(); // Clears ThreadLocal variable
SELECT("*");
FROM("BLOG");
return SQL();
}
private String selectPersonSql() {等价的sql语句:
BEGIN(); // Clears ThreadLocal variable
SELECT("P.ID, P.USERNAME, P.PASSWORD, P.FULL_NAME");
SELECT("P.LAST_NAME, P.CREATED_ON, P.UPDATED_ON");
FROM("PERSON P");
FROM("ACCOUNT A");
INNER_JOIN("DEPARTMENT D on D.ID = P.DEPARTMENT_ID");
INNER_JOIN("COMPANY C on D.COMPANY_ID = C.ID");
WHERE("P.ID = A.ID");
WHERE("P.FIRST_NAME like ?");
OR();
WHERE("P.LAST_NAME like ?");
GROUP_BY("P.ID");
HAVING("P.LAST_NAME like ?");
OR();
HAVING("P.FIRST_NAME like ?");
ORDER_BY("P.ID");
ORDER_BY("P.FULL_NAME");
return SQL();
}
"SELECT P.ID, P.USERNAME, P.PASSWORD, P.FULL_NAME, "动态拼接sql:
"P.LAST_NAME,P.CREATED_ON, P.UPDATED_ON " +
"FROM PERSON P, ACCOUNT A " +
"INNER JOIN DEPARTMENT D on D.ID = P.DEPARTMENT_ID " +
"INNER JOIN COMPANY C on D.COMPANY_ID = C.ID " +
"WHERE (P.ID = A.ID AND P.FIRST_NAME like ?) " +
"OR (P.LAST_NAME like ?) " +
"GROUP BY P.ID " +
"HAVING (P.LAST_NAME like ?) " +
"OR (P.FIRST_NAME like ?) " +
"ORDER BY P.ID, P.FULL_NAME";
private String selectPersonLike(Person p){
BEGIN(); // Clears ThreadLocal variable
SELECT("P.ID, P.USERNAME, P.PASSWORD, P.FIRST_NAME, P.LAST_NAME");
FROM("PERSON P");
if (p.id != null) {
WHERE("P.ID like #{id}");
}
if (p.firstName != null) {
WHERE("P.FIRST_NAME like #{firstName}");
}
if (p.lastName != null) {
WHERE("P.LAST_NAME like #{lastName}");
}
ORDER_BY("P.LAST_NAME");
return SQL();
}
Method | Description |
BEGIN()/RESET() | 重置ThreadLocal状态 |
SELECT(String) | select 参数 |
FROM(String) | from 表名 |
JOIN(String) INNER_JOIN(String) LEFT_OUTER_JOIN(String) RIGHT_OUTER_JOIN(String) |
表连接 |
WHERE(String) | where子句 |
OR() | or 子句 |
AND() | and 子句 |
GROUP_BY() | group by 子句 |
HAVING(String) | having 子句 |
ORDER_BY(String) | order by 子句 |
SQL() | 返回拼接的sql语句 |