Mybatis使用入门
代码构建
public interface UserMapper {
@Select("select * from user where id = 1")
User getUser(Integer id);
}
public static void main(String[] args) throws SQLException {
// 1. datasource配置
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setURL("jdbc:mysql://localhost:3306/test");
dataSource.setUser("root");
dataSource.setPassword("xxnydyxf");
dataSource.setCharacterEncoding("UTF-8");
dataSource.setServerTimezone("UTC");
// 2. 事物
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
// 3. 注册Mapper
configuration.addMapper(UserMapper.class);
// 4. 构建 SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
// 5. 使用
SqlSession session = sqlSessionFactory.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
User user = userMapper.getUser(1);
System.out.println(user.getAge());
}
// 分析
1.Datasource配置
3. 注册
// 注册Mapp类
configuration.addMapper(UserMapper.class);
/**
* 配置信息
*/
public class org.apache.ibatis.session.Configuration{
//...
public <T> void addMapper(Class<T> type) {
mapperRegistry.addMapper(type);
}
//...
}
public class org.apache.ibatis.binding.MapperRegistry{
//...
//
public <T> void addMapper(Class<T> type) {
if (type.isInterface()) {// 如果是接口
if (hasMapper(type)) {// 判断是否已经存在
throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
}
boolean loadCompleted = false;
try {
// 缓存 此时指示暂时保存,并不生成代理
knownMappers.put(type, new MapperProxyFactory<>(type));
// It's important that the type is added before the parser is run
// otherwise the binding may automatically be attempted by the
// mapper parser. If the type is already known, it won't try.
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
parser.parse();
loadCompleted = true;
} finally {
if (!loadCompleted) {
knownMappers.remove(type);
}
}
}
}
//...
}
4. 构建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
// new 一个 DefaultSqlSessionFactory
public class SqlSessionFactoryBuilder {
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
}
// 没啥好说的
public class DefaultSqlSessionFactory implements SqlSessionFactory {
private final Configuration configuration;
public DefaultSqlSessionFactory(Configuration configuration) {
this.configuration = configuration;
}
}