Mybatis(持久层框架)
框架介绍
三层架构
持久层技术总结
概述
Mybatis入门
注意事项
使用Mybatis,Pom需要导入的坐标
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependencies>
在resources目录下创建文件SqlMapConfig.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="mysql">
<environment id="mysql">
<transactionManager type="JDBC">
</transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="itheima/dao/IUserDao.xml"></mapper>
</mappers>
</configuration>
在resources目录下创建itheima/dao的目录,创建IuserDao.xml
映射配置文件的目录结构和dao接口的包结构一致的话,就无需再写接口的实现类,如IuserDao.xml
入门案例(使用xml)
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(is);
SqlSession session = factory.openSession();
IUserDao userDao = session.getMapper(IUserDao.class);
List<User> list = userDao.findAll();
for (User user : list) {
System.out.println(user);
}
session.close();
is.close();
使用注解方式替代xml
将IUserDao.xml文件删除,同时在Iuserdao接口的方法上加上注解
同时在SqlMapConfig.xml文件中,将映射改成指定为class
<mapper class="itheima.dao.IUserDao"></mapper>
可以为接口实现一个类 通过调用session对象的selectList方法 参数为:指定接口的方法 测试代码
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(is);
IUserDao userDao = new UserDaoImpl(factory);
List<User> list = userDao.findAll();
for (User user : list) {
System.out.println(user);
}
is.close();
设计模式分析
|