mybatis 入门代码
-
通过 Resources 工具类将 mybatis-config.xml 配置文件读入 InputStream(Reader) 。
-
再通过SqlSessionFactoryBuilder 建造类使用 InputStream(Reader) 创建 SqlSessionFactory 工厂对象。
-
在创建SqlSessionFactory 对象的过程中 , 首先解析 mybatis-config.xml 配置 文件,读取配置文件中的 mappers(dao).xml 配置后会读取全部的 Mapper(dao).xml 进行具体方法的解析, 在这些解析完成后,SqlSessionFactory就包含了所有的属性配置和执行 SQL 的信息。 使用时通过 SqlSessionFactory 工厂对象获取一个 SqlSession。
-
通过 SqlSession 的 selectList 方法(传递全限定类名.方法名id名)查找到 mapper(dao)XXX.xml配置文件指 中 id= ” findall” 的方法,执行 SQL 查询 。(或者通过 SqlSession 的 getMapper方法(传递接口名.class)查找到 mapper(dao)XXX.xml配置文件指 中 id= ” findall” 的方法,执行 SQL 查询 )
mybatis在使用代理dao的方式实现增删改查时做什么事呢?
只有两件事:
第一:创建代理对象
第二:在代理对象中调用selectList -
MyBatis 底层使用 JDBC 执行 SQL,获得查询结果集 ResultSet 后,根据resultType 的配置将结果映射为 User类型的集合 , 返回查询结果。
-
这样就得到了最后的查询结果users,简单将结果输出到控制台。
-
最后一定不要忘记关闭 SqlSession 和in,否则会因为连接没有关闭导致数据库连接数过 多,造成系统崩旗。
class Resources
class SqlSessionFactoryBuilder
interface SqlSessionFactory
interface SqlSession读取配置文件
配置文件:用到的技术就是解析xml文件技术。
(此处用的是dom4j解析xml文件)
- 连接数据库的配置信息,可以创建Connection对象
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/eesy"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
- 有了它,就有了映射配置信息
<mappers>
<mapper resource="com/itheima/dao/IUserdao.xml"/>
</mappers>
- 映射配置信息。 有了它就有了执行的SQL语句,就可以获取PreparedStatement. 此配置中还有封装的实体类全限定类名。
id 属性:定义了当前 SELECT 查询的唯一一个 id ;
resultType:定义了当前查询的返回值类型;
<mapper namespace="com.itheima.dao.IUserdao">
<!-- 配置查询所有操作 -->
<select id="findall" resultType="com.itheima.domain.User">
select * from user
</select>
</mapper>
2.
创建代理对象的分析
//4.使用SqlSession创建Dao接口的代理对象
IUserdao userDao = session.getMapper(IUserdao.class);
。