作者:紫藤雨2502915477 | 来源:互联网 | 2023-10-10 23:17
- 导入坐标,Mysql驱动与Mybatis的坐标(junit和log4j)
- 创建相应的表以及与表对应的pojo,其中pojo的属性要与表中的表头相同。生成get和set方法已经tostring方法
- 编写映射文件UserMapper.xml。如:
<?xml version&#61;"1.0" encoding&#61;"UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace&#61;"userMapper">
<select id&#61;"findAll" resultType&#61;"com.qc.domain.User">select * from User</select>
</mapper>
- 编写核心文件SqlMapConfig.xml
<?xml version&#61;"1.0" encoding&#61;"UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default&#61;"development">
<environment id&#61;"development"><transactionManager type&#61;"JDBC"></transactionManager><dataSource type&#61;"POOLED"><property name&#61;"driver" value&#61;"com.mysql.jdbc.Driver"/><property name&#61;"url" value&#61;"jdbc:mysql://localhost:3306/test"/><property name&#61;"username" value&#61;"root"/><property name&#61;"password" value&#61;"root"/></dataSource></environment>
</environments>
</configuration>
<mappers><mapper resource&#61;"路径"></mapper>
</mappers>
- 编写测试代码
InputStream resourceAsStream &#61; Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory &#61; new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession &#61; sqlSessionFactory.openSession();
List<User> userList &#61; sqlSession.selectList("userMapper.findAll");
sqlSession.close();
参考视频&#xff1a;https://www.bilibili.com/video/BV1WZ4y1P7Bp?p&#61;149&spm_id_from&#61;pageDriver