PS:XML文件的层次结构不能调到顺序,如果颠倒,会解析失败
3. 通过程序加载
常用于对数据库密码进行解密,配置文件中配置密文,程序解析成明文之后再传给Mybatis
properties.setProperty("username", decode(properties.getProperty("username")));
properties.setProperty("password", decode(properties.getProperty("password")));
return new SqlSessionFactoryBuilder().build(congfigXMl, properties);
使用${name}
用于设置Mybatis的行为,是Mybatis中最复杂的配置
给类的全限定名起别名,这样就可用很简短的名称去指代它
public enum Male {
MALE(2, "男"), FAMALE(3, "女");
private final static Map indexes = new HashMap();
static {
for (Male male : Male.values()) {
indexes.put(male.getCode(), male);
}
}
public static Male getMale(int code) {
return indexes.get(code);
}
private final int code;
private final String desc;
//get set
}
// typeHandler
@MappedTypes({Male.class})
@MappedJdbcTypes({JdbcType.TINYINT})
public class MaleTypeHandler implements TypeHandler {
public void setParameter(PreparedStatement preparedStatement, int i, Male male, JdbcType jdbcType) throws SQLException {
preparedStatement.setInt(i, male.getCode());
}
public Male getResult(ResultSet resultSet, String s) throws SQLException {
return Male.getMale(resultSet.getInt(s));
}
public Male getResult(ResultSet resultSet, int i) throws SQLException {
return Male.getMale(resultSet.getInt(i));
}
public Male getResult(CallableStatement callableStatement, int i) throws SQLException {
return Male.getMale(callableStatement.getInt(i));
}
}
// 配置Handler
//使用Handler
typeHandler="com.demo.mybatis.handler.MaleTypeHandler"/>
public class MyObjectFactory extends DefaultObjectFactory {
@Override
public void setProperties(Properties properties) {
System.out.println("setProperties:" + properties);
super.setProperties(properties);
}
@Override
public T create(Class type) {
System.out.println("create:" + type);
return super.create(type);
}
@Override
public T create(Class type, List> constructorArgTypes, List
(2)配置ObjecFactory
type="com.demo.mybatis.handler.MyObjectFactory">
name="name" value="MyObjectFactory"> //通过setProperties传到ObjectFactory
配置环境可以注册多个数据源,每个数据源包含如下两个部分:
transactionManager 中的type有三种属性配置:
Mybatis提供的四种dataSource :
public class DBCPDataSourceFactory implements DataSourceFactory { private Properties properties; public void setProperties(Properties properties) { this.properties = properties; } public DataSource getDataSource() { try { //使用apache的dbcp数据源 return BasicDataSourceFactory.createDataSource(properties); } catch (Exception e) { throw new RuntimeException(e); } } }