第一步: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://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="newpassword"/>
</dataSource>
</environment>
</environments>
<!--接口绑定-->
<mappers>
<mapper resource="com/cup/wang/dao/UserMapper.xml"/>
<!-- <mapper resource="UserMapper.xml"/>-->
</mappers>
</configuration>
第二步:SqlSessionFactory实例化
里面的配置如下:
package com.cup.wang.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.IOException;
import java.io.InputStream;
//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 (IOException e){
e.printStackTrace();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
public static SqlSession getSession(){
return sqlSessionFactory.openSession();
}
}
package com.cup.wang.pojo;
//实体类
public class User {
private int id;
private String name;
private String pwd;//注意,这里要和连接的表格列名一一对应(不对应也可以,通过,在UserMapper.xml中通过结果集映射解决)
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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
package com.cup.wang.dao;
import com.cup.wang.pojo.User;
import java.util.List;
import java.util.Map;
public interface UserMapper {
//模糊查询
List<User> getUserListLike(String value);
//查询全部用户
List<User> getUserList();
//根据id查询用户
User getUserById(int id);
User getUserById2(Map<String,Object> map);
//insert一个用户
int addUser(User user);
//万能的Map
User addUser2(Map<String,Object> map);
//修改用户
int updateUser(User user);
//删除用户
int deleteUser(int id);
}
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="com.cup.wang.dao.UserMapper">
<!--模糊查询语句-->
<select id="getUserListLike" resultType="com.cup.wang.pojo.User">
select * from mybatis.user where name like #{value};
</select>
<!--select查询语句-->
<select id="getUserList" resultType="com.cup.wang.pojo.User">
<!--id:方法名称 resultType:返回值类型(类名)-->
select * from mybatis.user
</select>
<select id="getUserById" parameterType="int" resultType="com.cup.wang.pojo.User">
<!--parameterType:参数类型-->
select * from mybatis.user where id = #{id};
</select>
<select id="getUserById2" parameterType="map" resultType="com.cup.wang.pojo.User">
<!--parameterType:参数类型-->
select * from mybatis.user where id = #{id} and name = #{name};
</select>
<!--对象中的属性,可以直接取出来-->
<insert id="addUser" parameterType="com.cup.wang.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},#{userpwd});
</insert>
<update id="updateUser" parameterType="com.cup.wang.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id = #{id};
</update>
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id};
</delete>
</mapper>
package com.cup.wang.dao;
import com.cup.wang.pojo.User;
import com.cup.wang.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class UseDaoTest {
@Test
public void getUserLike(){
SqlSession sqlSession = MybatisUtils.getSession();
//第二步:执行SQL
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserListLike("%杨%");
for (User user : userList){
System.out.println(user);
}
sqlSession.close();
}
@Test
public void test(){
//第一步:获得SQLSession对象
SqlSession sqlSession = null;
try{
sqlSession = MybatisUtils.getSession();
//第二步:执行SQL
//方式一:getMapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
//方式二:
// List userList = sqlSession.selectList("com.cup.wang.dao.UserDao.getUserList");
for (User user : userList){
System.out.println(user);
}
}catch (Exception e){
e.printStackTrace();
}finally {
//关闭SqlSession
sqlSession.close();
}
}
@Test
public void getUserById(){
//第一步:获得SQLSession对象
SqlSession sqlSession = MybatisUtils.getSession();
//第二步:执行SQL
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
// @Test
// public void getUserById2(){
// //第一步:获得SQLSession对象
// SqlSession sqlSession = MybatisUtils.getSession();
//
// //第二步:执行SQL
// UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// Map map = new HashMap<>();
//
// map.put("id",2);
// User user = mapper.addUser2(map);
// System.out.println(user);
//
// sqlSession.close();
//
// }
//增删改需要提交事务
@Test
public void addUser(){
//第一步:获得SQLSession对象
SqlSession sqlSession = MybatisUtils.getSession();
//第二步:执行SQL
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int user = mapper.addUser(new User(5, "小钱", "321123"));
if (user > 0){
System.out.println("插入成功!!!");
}
//第三步:提交事务
sqlSession.commit();
sqlSession.close();
}
// @Test
// public void addUser2(){
// //第一步:获得SQLSession对象
// SqlSession sqlSession = MybatisUtils.getSession();
//
// //第二步:执行SQL
// UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//
// Map map = new HashMap();
//
// map.put("userId",5);
// map.put("userName","小李");
// map.put("userpwd","1433223");
//
// User user2 = mapper.addUser2(map);
//
//
// //第三步:提交事务
// sqlSession.commit();
// sqlSession.close();
// }
//增删改需要提交事务
@Test
public void updateUser(){
//第一步:获得SQLSession对象
SqlSession sqlSession = MybatisUtils.getSession();
//第二步:
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int user = mapper.updateUser(new User(4, "小邓", "233233"));
//第三步:
sqlSession.commit();
sqlSession.close();
}
//增删改需要提交事务
@Test
public void deleteUser(){
//第一步:获得SQLSession对象
SqlSession sqlSession = MybatisUtils.getSession();
//第二步
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int deleteUser = mapper.deleteUser(4);
//第三步
sqlSession.commit();
sqlSession.close();
}
}
如此一来,就可以简单的实现Mybatis对数据库的增删改查
补充:maven的配置和数据库连接
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>Mybatis-study</artifactId>
<groupId>com.cup</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties
**/ *.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties
**/ *.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
<modelVersion>4.0.0</modelVersion>
<artifactId>mybatis-01</artifactId>
</project>
数据库连接过程:
填写用户和密码:
连接成功
选择表格:
测试以id查询信息,成功!!!
配置过程中遇到各种问题,可参考前一篇文章
PS:墙裂安利B站Up主"狂神说Java",本次实践全部以Up主视频为基础