2.配置sqlsessionfactory
mybatis 的sqlsessionfactory 接口除了使用基于 xml 的配置创建外也可以通过 java api 编程式地被创建。每个在 xml 中配置的元素,都可以编程式的创建。
使用 java api 创建 sqlsessionfactory,代码如下:
public static sqlsessionfactory getsqlsessionfactoryusingjavaapi() {
if (javasqlsessionfactory == null) {
try {
datasource datasource = datasourcefactory.getdatasource();
transactionfactory transactionfactory = new jdbctransactionfactory();
environment environment = new environment("development", transactionfactory, datasource);
configuration configuration = new configuration(environment);
configuration.gettypealiasregistry().registeralias("student", student.class);
configuration.gettypehandlerregistry().register(phonetypehandler.class);
configuration.addmapper(studentmapper.class);
javasqlsessionfactory = new sqlsessionfactorybuilder().build(configuration);
} catch (exception e) {
throw new runtimeexception(e);
}
}
return javasqlsessionfactory;
}