Mybatis自学(1)
1、什么是MyBatis
SQL语句中的insert语句返回值是插入的数据的条数,若插入失败,则返回值为0。
实体类:属性私有、方法公有。
补充
2、第一个Mybatis程序
搭建环境
- 搭建数据库
create DATABASE mybatis;
use mybatis;
create table user(
id int(20) not null,
name varchar(30) DEFAULT null,
pwd VARCHAR(30) DEFAULT null,
PRIMARY KEY(id)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT
INTO USER
VALUES
(1,'*','123456'),
(2,'昊炜','142536'),
(3,'磊子','512364')
- 新建项目
a)新建一个普通的maven项目
b)删除src目录
c)导入maven依赖
<!-- 导入依赖。-->
<dependencies>
<!-- mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!-- mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
</dependencies>
d)创建一个模块
- 编写mybatis的核心配置文件
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.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
</configuration>
- 编写 mybatis的工具类
MybatisUtils.java
package top.gujiakai.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
/**
* Author: Gu Jiakai
* Date: 2021/10/15 10:18
* FileName: MybatisUtils
* Description:
*/
//SqlSessionFactory -->sqlsession
public class MybatisUtils {
//提升作用域
private static SqlSessionFactory sqlSessionFactory;
static{
try {
//使用Mybatis第一步:获取sqLsessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
// 既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
public static SqlSession getSqlSession(){
// SqlSession sqlSession = sqlSessionFactory.openSession();
// return sqlSession;
return sqlSessionFactory.openSession();
}
}
e)编写代码
- 实体类
package top.gujiakai.pojo;
/**
* Author: Gu Jiakai
* Date: 2021/10/15 11:04
* FileName: User
* Description:
*/
//实体类
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
- Dao接口
UserDao.java
package top.gujiakai.dao;
import top.gujiakai.pojo.User;
import java.util.List;
/**
* Author: Gu Jiakai
* Date: 2021/10/15 11:07
* FileName: UserDao
* Description:
*/
public interface UserDao {
List<User> getUserList();
}
- 接口实现类
接口实现类由原来的UserDaolmpl转变为一个Mapper配置文件。
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">
<!--namespace绑定一个对应的Dao/Mapper接口-->
<mapper namespace="top.gujiakai.dao.UserDao">
<!-- select查询语句-->
<select id="getUserList" resultType="top.gujiakai.pojo.User">
select * from mybatis.user
</select>
</mapper>
f)测试
- junit测试
报错集合:
a)org.apache.ibatis.binding.BindingException: Type interface top.gujiakai.dao.UserDao is not known to the MapperRegistry.
没有在mybatis-config.xml中配置mapper。
核心配置文件中注册mappers。
b)Could not find resource top/gujiakai/dao/UserMapper.xml
资源过滤问题
- junit测试
UserDaoTest.java
package top.gujiakai.dao;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import top.gujiakai.pojo.User;
import top.gujiakai.utils.MybatisUtils;
import java.util.List;
/**
* Author: Gu Jiakai
* Date: 2021/10/15 11:21
* FileName: UserDaoTest
* Description:
*/
public class UserDaoTest {
@Test
public void test(){
// 第1步:获取sqlsession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
// 方式一:getMapper
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
for(User user:userList){
System.out.println(user);
}
//关闭sqlSession
sqlSession.close();
}
}
3、增删改查实现
- 增删改需要提交事务。
UserMapper.java
package top.gujiakai.dao;
import top.gujiakai.pojo.User;
import java.util.List;
/**
* Author: Gu Jiakai
* Date: 2021/10/15 11:07
* FileName: UserDao
* Description:
*/
public interface UserMapper {
// 查询全部用户。
List<User> getUserList();
// 根据ID查询用户。
User getUserByID(int id);
//insert一个用户。
int addUser(User user);
// 修改用户。
int updateUser(User user);
//删除一个用户。
int deleteUser(int id);
}
UserMapper.xml
<?xml version="1.0" encoding="GBK" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace绑定一个对应的Dao/Mapper接口-->
<mapper namespace="top.gujiakai.dao.UserMapper">
<!-- select查询语句-->
<select id="getUserList" resultType="top.gujiakai.pojo.User">
select * from mybatis.user
</select>
<select id="getUserByID" parameterType="int" resultType="top.gujiakai.pojo.User">
select * from mybatis.user where id= #{id}
</select>
<!-- 对象中的属性可以直接取出来。-->
<insert id="addUser" parameterType="top.gujiakai.pojo.User">
insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd})
</insert>
<update id="updateUser" parameterType="top.gujiakai.pojo.User">
update mybatis.user
set name=#{name},pwd=#{pwd}
where id=#{id};
</update>
<delete id="deleteUser" parameterType="top.gujiakai.pojo.User">
delete from mybatis.user where id=#{id}
</delete>
</mapper>
UserDaoTest.java
package top.gujiakai.dao;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import top.gujiakai.pojo.User;
import top.gujiakai.utils.MybatisUtils;
import java.util.List;
/**
* Author: Gu Jiakai
* Date: 2021/10/15 11:21
* FileName: UserDaoTest
* Description:
*/
public class UserDaoTest {
@Test
public void test() {
// 第1步:获取sqlsession对象
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtils.getSqlSession();
// 方式一:getMapper
// UserMapper userDao = sqlSession.getMapper(UserMapper.class);
// List<User> userList = userDao.getUserList();
// 方式二:
List<User> userList = sqlSession.selectList("top.gujiakai.dao.UserMapper.getUserList");
for (User user : userList) {
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
//关闭sqlSession
sqlSession.close();
}
}
@Test
public void getUserByID(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserByID(1);
System.out.println(user);
sqlSession.close();
}
//增删改需要提交事务。
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int res = mapper.addUser(new User(4, "阿豪", "12542"));
if(res>0){
System.out.println("插入成功!");
}
//提交事务。
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(4,"小辫子","123456"));
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(3);
sqlSession.commit();
sqlSession.close();
}
}
4、错误排查指导
读错从后往前读。
5、Map和模糊查询拓展
UserMapper.java
package top.gujiakai.dao;
import top.gujiakai.pojo.User;
import java.util.List;
import java.util.Map;
/**
* Author: Gu Jiakai
* Date: 2021/10/15 11:07
* FileName: UserDao
* Description:
*/
public interface UserMapper {
List<User> getUserLike(String value);
// 查询全部用户。
List<User> getUserList();
// 根据ID查询用户。
User getUserByID(int id);
User getUserByID2(Map<String,Object> map);
//insert一个用户。
int addUser(User user);
int addUser2(Map<String,Object> map);
// 修改用户。
int updateUser(User user);
//删除一个用户。
int deleteUser(int id);
}
UserMapper.xml
<?xml version="1.0" encoding="GBK" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace绑定一个对应的Dao/Mapper接口-->
<mapper namespace="top.gujiakai.dao.UserMapper">
<select id="getUserLike" resultType="top.gujiakai.pojo.User">
select * from mybatis.user where name like #{value}
</select>
<!-- select查询语句-->
<select id="getUserList" resultType="top.gujiakai.pojo.User">
select * from mybatis.user
</select>
<select id="getUserByID" parameterType="int" resultType="top.gujiakai.pojo.User">
select * from mybatis.user where id= #{id}
</select>
<select id="getUserByID2" parameterType="map" resultType="top.gujiakai.pojo.User">
select * from mybatis.user where id= #{helloID}
</select>
<!-- 对象中的属性可以直接取出来。-->
<insert id="addUser" parameterType="top.gujiakai.pojo.User">
insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd})
</insert>
<!--
传递map的key
-->
<!-- <insert id="addUser2" parameterType="map">-->
<!-- insert into mybatis.user(id,name,pwd) values(#{userID},#{userName},#{passWord})-->
<!-- </insert>-->
<update id="updateUser" parameterType="top.gujiakai.pojo.User">
update mybatis.user
set name=#{name},pwd=#{pwd}
where id=#{id};
</update>
<delete id="deleteUser" parameterType="top.gujiakai.pojo.User">
delete from mybatis.user where id=#{id}
</delete>
</mapper>
UserDaoTest.java
package top.gujiakai.dao;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import top.gujiakai.pojo.User;
import top.gujiakai.utils.MybatisUtils;
import java.util.HashMap;
import java.util.List;
/**
* Author: Gu Jiakai
* Date: 2021/10/15 11:21
* FileName: UserDaoTest
* Description:
*/
public class UserDaoTest {
@Test
public void getUserLike(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserLike("%蔡%");
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void test() {
// 第1步:获取sqlsession对象
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtils.getSqlSession();
// 方式一:getMapper
// UserMapper userDao = sqlSession.getMapper(UserMapper.class);
// List<User> userList = userDao.getUserList();
// 方式二:
List<User> userList = sqlSession.selectList("top.gujiakai.dao.UserMapper.getUserList");
for (User user : userList) {
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
//关闭sqlSession
sqlSession.close();
}
}
@Test
public void getUserByID(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserByID(1);
System.out.println(user);
sqlSession.close();
}
@Test
public void getUserByID2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Object> map = new HashMap<String,Object>();
map.put("helloID",1);
mapper.addUser2(map);
sqlSession.close();
}
//增删改需要提交事务。
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int res = mapper.addUser(new User(4, "阿豪", "12542"));
if(res>0){
System.out.println("插入成功!");
}
//提交事务。
sqlSession.commit();
sqlSession.close();
}
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Object> map = new HashMap<>();
map.put("userID",5);
map.put("userName","caiwei2333");
map.put("passWord","123456");
mapper.addUser2(map);
sqlSession.close();
}
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(4,"小辫子","123456"));
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(3);
sqlSession.commit();
sqlSession.close();
}
}