優化:
1.可以將配置信息單獨放入 db.properties文件中,然後在動態引入
db.properties:
k=v;
<configuration>
<properties resource="db.properties"/>
引入之後,使用${key};
2.MyBatias全局參數,在config.xml設置
<settings>
<setting name="" value=""/>
</settings>
3.別名
a.設置單個別名
b.設置批量別名
<!-- 設置別名(忽略大小寫) -->
<typeAliases>
<!-- 單個 -->
<typeAlias type="com.user.Student" alias="student"/>
<!-- 批量 ,以下會自動將該包中的所有類批量定義別名,別名就是類名-->
<package name="com.user"/>
</typeAliases>
處理自定義別名外,Mybatias還內置了一些常見類的別名
類型處理器(類型轉換器)
1.MyBatis自帶一些常見的類型處理器
2.自定義Mybatias類型處理器
java-數據庫(jdbc類型)
實例:
實體類Student:boolean stuSex(true:男;false:女)
表student: number stuSex(1:男;0:女)
自定義類型轉換器(boolean - number)步驟:
a.創建轉換器
需要實現TypeHandler接口(有個實現類BaseTypeHandler)
package com.converter;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
public class BoolAndIntConverter extends BaseTypeHandler<Boolean> {
/*
* i:PreparedStatement對象操作參數的位置
* parameter:java的值
* jdbcType:jdbc操作的數據庫類型
*/
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Boolean parameter, JdbcType jdbcType)
throws SQLException {
if(parameter) {
ps.setInt(i, 1);
}else {
ps.setInt(i, 0);
}
}
@Override
public Boolean getNullableResult(ResultSet rs, String columnName) throws SQLException {
int sexNum = rs.getInt(columnName);
return sexNum==1?true:false;
}
@Override
public Boolean getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
int sexNum = rs.getInt(columnIndex);
return sexNum==1?true:false;
}
@Override
public Boolean getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
int sexNum = cs.getInt(columnIndex);
return sexNum==1?true:false;
}
}
b.配置config.xml
c.配置mapper.xml
需要注意的問題:需要大寫INTEGER