mybatis环境搭建**
起步依赖
1、mybatis的引入
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
2、数据库
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
3、日志信息
<!--日志-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
4、测试
<!--测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
数据库的xml配置
<environments default="mysql">
<!--配置mysql的环境-->
<environment id="mysql">
<!--配置事务类-->
<transactionManager type="JDBC"></transactionManager>
<!--连接池-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/eesy_mybatis"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
开发方式
注解开发(映射配置文件)
<mappers>
<mapper class="com.demo.dao.IUseDao"></mapper>
</mappers>
public interface IUseDao {
@Select("select * from user")
List<User> findAll();
}
xml开发则通过resource引入
测试类(工厂方式)
InputStream inputStream= Resources.getResourceAsStream("SqlaMapConfig.xml");
//2.创建SqlSessionFactory工厂
SqlSessionFactoryBuilder builder= new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory=builder.build(inputStream);
//3.使用工厂生产SqlSession对象
SqlSession session=sqlSessionFactory.openSession();
//4.使用SqlSession创建Dao接口的代理对象
IUseDao useDao= session.getMapper(IUseDao.class);
//5.使用代理对象执行方法
List<User> users= useDao.findAll();
for(User user:users){
System.out.println(user);
}
session.close();
inputStream.close();