mybatis最基本的使用
2022-01-18 本文已影响0人
4陈雨泽4
1.新建配置文件mybatis-config.xml(src/main/resources/mybatis-config.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="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://192.168.2.46:3306/myserver" />
<property name="username" value="admin" />
<property name="password" value="00000000" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml" />
</mappers>
</configuration>
2.在第1步的目录下,再建一个UserMapper.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.studyserver.module.login.mapper.UserMapper">
<insert id="addUser">
insert into user (phone, password)
values (#{phone}, #{password})
</insert>
<insert id="addToken">
insert into user_token (phone, token)
values (#{phone}, #{token})
</insert>
<select id="findAll" resultType="com.studyserver.module.login.dto.UserDTO">
select * from user
</select>
</mapper>
3.pom.xml文件,引入
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
4.在具体使用的地方添加接口
截屏2022-01-18 上午11.27.03.png
5.在controller中,获取SqlSession
private SqlSession getSqlSession() throws Exception {
String config = "mybatis-config.xml";
// 这里的Resources是org.apache.ibatis.io.Resources
InputStream inputStream = Resources.getResourceAsStream(config);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
return sqlSession;
}
6.用mapper调用方法,查询数据
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<UserDTO> all = mapper.findAll();
for (int i = 0; i < all.size(); i++) {
UserDTO o = all.get(i);
if (o.getPhone().equals(registerDTO.getPhone())) {
// 用户已经存在
return RestResponse.build(CommonResponseCode.DATA_EXISTS);
}
}
all就是查询出来的结果集
7.操作完之后,需要提交session事务
sqlSession.commit();
sqlSession.close();