MyBatis入门
学习内容:
1、 Mybatis配置文件
2、 XML法
3、 注解法
1.Mybatis基本配置文件
无论是框架还是原生的jdbc,配置文件都离不开最基本的
- driver
- url
- username
- password
<?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.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/firstmybatis?serverTimezone=Asia/Shanghai"/>
<property name="username" value="root"/>
<property name="password" value="zhengyunyu524"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/imis/dao/IUserDao.xml"/>
</mappers>
</configuration>
2.XML形式
对应的IUserDao.xml
<?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.imis.dao.IUserDao">
<!-- 配置查询所有 -->
<select id="queryAll" resultType="com.imis.pojo.User">
select * from user
</select>
</mapper>
resultType指明查询之后的封装
public static void main(String[] args) throws Exception {
//1读取配置文件
InputStream inputStream= Resources.getResourceAsStream("SqlMapConfig.xml");
//2创建sqlsessionfactory工厂
SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();
SqlSessionFactory factory=sqlSessionFactoryBuilder.build(inputStream);
//3使用工厂生产sqlsession对象
SqlSession sqlSession = factory.openSession();
//4使用sqlsession创建dao接口代理对象
IUserDao iUserDao=sqlSession.getMapper(IUserDao.class);
//5使用代理对象执行方法
List<User> users = iUserDao.queryAll();
for (User user:users){
System.out.println(user);
}
//6释放资源
sqlSession.close();
inputStream.close();
}
3.注解形式
注解的SqlMapConfig.xml文件配置与xml的基本一致,只需要修改mapper
<?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.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/firstmybatis?serverTimezone=Asia/Shanghai"/>
<property name="username" value="root"/>
<property name="password" value="zhengyunyu524"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- <mapper resource="com/imis/dao/IUserDao.xml"/>-->
<mapper class="com.imis.dao.IUserDao"/>
</mappers>
</configuration>
同时在Dao中以注解的形式写上sql语句
@Select("select * from user")
List<User> queryAll();