SqlSessionFactory
- 首先理解mybatis的原理榨惠,并不是從spring的集成開始泊脐。而每一個(gè)mybatis的應(yīng)用程序都是由SqlSessionFactory為核心開始伟件,而SqlSessionFactory又是由SqlSessionFactoryBuilder對(duì)象獲取而來润梯。
SqlSessionFactoryBuilder可以從XML配置文件中加載配置信息從而創(chuàng)建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>
-
運(yùn)行結(jié)果
可以看出SqlSessionFactoryBuilder是整個(gè)入口的核心類,他主要承擔(dān)了mybatis的配置文件的加載肝谭,解析掘宪,以及內(nèi)部構(gòu)建等職責(zé)蛾扇。