1.首先在src上创建po,database,mapper三个包。
在database包下面创建一个DataConnection类,代码如下:
public class DataConnection { private String resource="SqlMapConfig.xml"; private SqlSessionFactory sqlSessionFactory; private SqlSession sqlSession; public SqlSession getSqlSession() throws IOException { InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); sqlSession=sqlSessionFactory.openSession(); return sqlSession; } }
2.同时,我们需要在xml导入相关依赖。
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.13</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
然后我们需要创建一个config目录来存放核心配置文件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>
<!-- 和spring整合后 environments配置将废除-->
<environments default="mysql">
<environment id="mysql">
<!-- 使用jdbc事务管理-->
<transactionManager type="JDBC"/>
<!-- 数据库连接池-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssm_db?characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="sqlmap/UserInfoMapper.xml"/>
</mappers>
</configuration>
<mapper resource="sqlmap/UserInfoMapper.xml"/>
注意:第一次写入
"http://mybatis.org/dtd/mybatis-3-config.dtd">
3.连接数据库,在po层里面创建相关实列。
注意,一定要将config标志为路径,操作方法为:https://blog.csdn.net/bb_111/article/details/127220665
4.根据教材相关实列,向userInferMapper中写入sql语句,在test中写入测试方法。