SqlSessionFactory
- 首先理解mybatis的原理,并不是从spring的集成开始。而每一个mybatis的应用程序都是由SqlSessionFactory为核心开始,而SqlSessionFactory又是由SqlSessionFactoryBuilder对象获取而来。
SqlSessionFactoryBuilder可以从XML配置文件中加载配置信息从而创建SqlSessionFactory。
demo例子:
MybatisHelloWorld:
public class MybatisHelloWorld {
public static void main(String[] args) throws Exception{
String resource = "src/main/resource/Configuration.xml";
FileInputStream file = new FileInputStream(resource);
Reader reader = new InputStreamReader(file);
try {
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlMapper.openSession();
try {
UserVo user = (UserVo) session.selectOne("com.hhd.mybatis.repository.UserMapper.getUser", "1");
System.out.println(user.getId() + "," + user.getName());
} finally {
session.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
UserMapper:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hhd.mybatis.repository.UserMapper">
<select id="getUser" parameterType="String" resultType="com.hhd.mybatis.vo.UserVo">
select id,name from user where id = #{id}
</select>
</mapper>
UserMapper:
public interface UserMapper {
UserVo getUser(String id);
}
UserVo:
public class UserVo implements Serializable {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Configuration.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://#########.3:10001/mybatis?useUnicode=true"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/hhd/mybatis/mapper/UserMapper.xml"/>
</mappers>
</configuration>
-
运行结果
image.png -
可以看出SqlSessionFactoryBuilder是整个入口的核心类,他主要承担了mybatis的配置文件的加载,解析,以及内部构建等职责。
网友评论