Mybatis实现基本的增删改查
一、Mybatis是什么?
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
二、步骤
1.创建项目
- 新建一个Maven项目,并删除src文件夹,作为父工程
- 在父工程下新建Maven项目作为子工程
2.导入Maven依赖
在父工程的pom.xml文件中导入所需的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">
<modelVersion>4.0.0</modelVersion>
<!--父工程-->
<groupId>org.example</groupId>
<artifactId>MyBatis-Study</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>mybatis-01</module>
</modules>
<!--导入依赖-->
<!--mysql驱动-->
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
注:在父工程下创建的所有子工程不需要再次导入这些依赖
3.编写Mybatis核心配置文件
在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/mydb1?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="dao/UserMapper.xml"/>
</mappers>
</configuration>
4.编写Mybatis工具类
在Java文件下新建一个utils文件夹存放MyBatisUtils.java工具类
package utils;
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;
import static org.apache.ibatis.io.Resources.*;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//使用Mybatis第一步获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//从SqlSessionFactory中获取SqlSession
public static SqlSession getSqlSession() {
SqlSession sqlSession = sqlSessionFactory.openSession();
return sqlSession;
}
}
5.编写代码实现CRUD
1. 实体类
在Java文件下新建一个pojo文件夹存放User.java实体类
package pojo;
public class User {
private int id;
private String name;
private String gender;
private String birthday;
public User() {
}
public User(int id, String name, String gender, String birthday) {
this.id = id;
this.name = name;
this.gender = gender;
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", gender='" + gender + '\'' +
", birthday='" + birthday + '\'' +
'}';
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public String getBirthday() {
return birthday;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setGender(String gender) {
this.gender = gender;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
2. dao接口
在Java文件夹下新建一个dao文件夹,dao文件夹下新建一个UserMapper接口文件
package dao;
import pojo.User;
import java.util.List;
public interface UserMapper {
//查询全部用户
List<User> getUserList();
//根据ID查询用户
User getUserById(int id);
//插入一个用户
int addUser(User user);
//根据姓名删除用户
int delUser(String name);
//根据id修改用户
int updUser(User user);
}
3. 接口实现类
在dao文件夹下新建一个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绑定一个对应的Mapper接口-->
<mapper namespace="dao.UserMapper">
<!--id为对应的namespace中的方法名 resultType为返回值类型 parameterType为参数类型 -->
<!-- 查询全部用户-->
<select id="getUserList" resultType="pojo.User">
select * from student;
</select>
<!--根据ID查询用户-->
<select id="getUserById" parameterType="int" resultType="pojo.User">
select * from student where id=#{id}
</select>
<!--插入用户-->
<insert id="addUser" parameterType="pojo.User">
insert into student(id,name,gender,birthday) values(#{id},#{name},#{gender},#{birthday})
</insert>
<!--删除用户-->
<delete id="delUser" parameterType="String">
delete from student where name=#{name}
</delete>
<!--更新用户-->
<update id="updUser" parameterType="pojo.User">
update student set name=#{name},gender=#{gender},birthday=#{birthday} where id=#{id};
</update>
</mapper>
4. 测试类
Test文件夹下新建UserMapperTest测试类
package dao;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import pojo.User;
import utils.MybatisUtils;
import java.util.List;
public class UserMapperTest {
@Test
public void test(){
//获得SqlSession对象
SqlSession sqlSession= MybatisUtils.getSqlSession();
//执行sql
UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
List<User> userList=userMapper.getUserList();
for (User user:userList){
System.out.println(user);
}
sqlSession.close();
}
@Test
public void getUserById(){
SqlSession sqlSession=MybatisUtils.getSqlSession();
UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
User user=userMapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
@Test
//增删改需要提交事务
public void addUser(){
SqlSession sqlSession=MybatisUtils.getSqlSession();
UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
int res=userMapper.addUser(new User(10,"杨总","男","1999-10-03"));
if (res>0){
System.out.println("插入成功");
}
//提交事务
sqlSession.commit();
sqlSession.close();
}
@Test
public void delUser(){
SqlSession sqlSession=MybatisUtils.getSqlSession();
UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
int res=userMapper.delUser("杨总");
if (res>0){
System.out.println("删除成功");
}
sqlSession.commit();
sqlSession.close();
}
@Test
public void updUser(){
SqlSession sqlSession=MybatisUtils.getSqlSession();
UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
int res=userMapper.updUser(new User(9,"杨总","男","1999-10-03"));
if (res>0){
System.out.println("修改成功");
}
sqlSession.commit();
sqlSession.close();
}
}
附录
用到的数据库:
项目结构:
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/5035.html