Mybatis使用xml及纯注解实现增删改查操作
文章目录
- MyBatis 的基本使用
- 1 案例讲解: 使用xml文件配置,实现对数据的增删改查,MyBatis----xml配置使用
- (1)代码目录:
- 导入项目依赖
- (2)创建pojo类:
- (3)编写mybatis 核心配置文件: mybatis-config.xml
- (4)编写SQL映射文件:DeptMapper.xml
- (4)编写工具类:MyUtils.java
- (5)开始使用:App.java
- 2 案例演示:MyBatis的纯注解开发,实现对数据的增删改查。
- (1)将 DeptMapper.xml 文件全部进行注释即可
- (2) 将工具类 MyUtils.java 保留以下部分,其他注释掉即可
- (3)接口 DeptMapper 使用注解
- (4)App.java 进行运行
- 由以上2个案例,可以体会到纯注解开发的快捷之处,希望大家好好体会。
MyBatis 的基本使用
什么是 MyBatis ?
- MyBatis 是一款优秀的持久层框架,用于简化 JDBC 开发
- MyBatis 本是 Apache 的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github官网:https://mybatis.org/mybatis-3/zh/index.html
1 案例讲解: 使用xml文件配置,实现对数据的增删改查,MyBatis----xml配置使用
(1)代码目录:
id 列为自增长。
导入项目依赖
pom.xml 文件:
<?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>com.xbf</groupId>
<artifactId>mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.34</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
</dependencies>
</project>
(2)创建pojo类:
package com.xbf.pojo;
public class Dept implements java.io.Serializable{
private int id;
private String name;
private int age;
private String sex;
private String address;
public String getName() {
return name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Dept{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
(3)编写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"/>
<!-- 数据库连接相关配置 ,db.properties文件中的内容-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/demo01?useSSL=true&useUnicode=true&
characterEncoding=GBK"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.xbf.mapper"/>
</mappers>
</configuration>
(4)编写SQL映射文件:DeptMapper.xml
<?xml version="1.0" encoding="UTF8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xbf.mapper.DeptMapper">
<!-- 根据id查询图书信息 -->
<select id="selectAll" parameterType="Integer"
resultType="com.xbf.pojo.Dept">
SELECT * from table1
</select>
<!-- 新增-->
<insert id="insertDept" parameterType="com.xbf.pojo.Dept">
insert into table1(`name`,`age`,`sex`,`address`) values(#{name},#{age},#{sex},#{address})
</insert>
<!-- 删除-->
<delete id="deleteDept" parameterType="int">
delete from table1 where id=#{id}
</delete>
<!-- 修改-->
<update id="updateDept" parameterType="com.xbf.pojo.Dept">
update table1 set name=#{name},age=#{age},sex=#{sex},address=#{address} where id=#{id}
</update>
</mapper>
(4)编写工具类:MyUtils.java
package com.xbf.utils;
import com.xbf.mapper.DeptMapper;
import com.xbf.pojo.Dept;
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;
import java.util.List;
public class MyUtils {
public static SqlSession getSqlSession() {
SqlSession sqlSession = null;
try {
InputStream is =
Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory build =
new SqlSessionFactoryBuilder().build(is);
sqlSession = build.openSession();
} catch (IOException e) {
throw new RuntimeException(e);
}
return sqlSession;
}
//修改
public static void updateDept(int id, String name, int age, String sex,
String address, DeptMapper mapper, SqlSession sqlSession) {
//SqlSession sqlSession = getSqlSession();
Dept dept = new Dept();
dept.setId(id);
dept.setName(name);
dept.setAge(age);
dept.setSex(sex);
dept.setAddress(address);
mapper.updateDept(dept);
if (sqlSession != null) {
sqlSession.commit();
// sqlSession.close();
}
System.out.println("修改成功");
}
//插入数据
public static void insertDept(String name, int age, String sex,
String address, DeptMapper mapper, SqlSession sqlSession) {
//SqlSession sqlSession = getSqlSession();
Dept dept = new Dept();
dept.setName(name);
dept.setAge(age);
dept.setSex(sex);
dept.setAddress(address);
mapper.insertDept(dept);
if (sqlSession != null) {
sqlSession.commit();
// sqlSession.close();
}
System.out.println("插入成功");
}
//删除数据
public static void deleteDept(int id, DeptMapper mapper, SqlSession sqlSession) {
//SqlSession sqlSession = getSqlSession();
mapper.deleteDept(id);
if (sqlSession != null) {
sqlSession.commit();
// sqlSession.close();
}
System.out.println("删除成功");
}
}
(5)开始使用:App.java
package com.xbf;
import com.xbf.mapper.DeptMapper;
import com.xbf.pojo.Dept;
import com.xbf.utils.MyUtils;
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;
import java.util.List;
public class App {
public static void print(DeptMapper mapper) {
List<Dept> depts = mapper.selectAll();
for (Dept dept : depts) {
System.out.println(dept);
}
}
public static void main(String[] args) throws IOException {
SqlSession sqlSession = MyUtils.getSqlSession();
DeptMapper mapper = sqlSession.getMapper(DeptMapper.class);
//查询
print(mapper);
//增加
MyUtils.insertDept("熊21", 23, "男", "北京", mapper,sqlSession);
print(mapper);
//修改
MyUtils.updateDept(12, "熊5", 23, "男", "北京", mapper, sqlSession);
print(mapper);
//删除
MyUtils.deleteDept(11, mapper, sqlSession);
print(mapper);
sqlSession.close();
}
}
运行结果:注意,下图结果为博主多次测试的结果,和上面代码运行结果不一定完全符合。
2 案例演示:MyBatis的纯注解开发,实现对数据的增删改查。
在上一个案例的基础上进行修改:
(1)将 DeptMapper.xml 文件全部进行注释即可
(2) 将工具类 MyUtils.java 保留以下部分,其他注释掉即可
package com.xbf.utils;
import com.xbf.mapper.DeptMapper;
import com.xbf.pojo.Dept;
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;
import java.util.List;
public class MyUtils {
public static SqlSession getSqlSession() {
SqlSession sqlSession = null;
try {
InputStream is =
Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory build =
new SqlSessionFactoryBuilder().build(is);
sqlSession = build.openSession();
} catch (IOException e) {
throw new RuntimeException(e);
}
return sqlSession;
}
}
(3)接口 DeptMapper 使用注解
package com.xbf.mapper;
import com.xbf.pojo.Dept;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface DeptMapper {
@Select("select * from table1")
//查询所有
List<Dept> selectAll();
//添加
@Insert("insert into table1(`name`,`age`,`sex`,`address`) values(#{name},#{age},#{sex},#{address})")
int insertDept(@Param(value = "name") String name,
@Param(value = "age") int age,
@Param(value = "sex") String sex,
@Param(value = "address") String address);
//@Param(value="name")String name,@Param(value="hobby")String hobby
//根据id 删除记录
@Delete("delete from table1 where id=#{id}")
int deleteDept(Integer id);
//根据id修改信息
@Update("update table1 set name=#{name},age=#{age},sex=#{sex},address=#{address} where id=#{id}")
int updateDept(@Param(value = "id") Integer id,
@Param(value = "name") String name,
@Param(value = "age") int age,
@Param(value = "sex") String sex,
@Param(value = "address") String address);
}
(4)App.java 进行运行
package com.xbf;
import com.xbf.mapper.DeptMapper;
import com.xbf.pojo.Dept;
import com.xbf.utils.MyUtils;
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;
import java.util.List;
public class App {
public static void print(DeptMapper mapper) {
List<Dept> depts = mapper.selectAll();
for (Dept dept : depts) {
System.out.println(dept);
}
}
public static void main(String[] args) throws IOException {
SqlSession sqlSession = MyUtils.getSqlSession();
DeptMapper mapper = sqlSession.getMapper(DeptMapper.class);
//查询
print(mapper);
System.out.println("查询成功");
//增加
mapper.insertDept("熊21", 23, "男", "北京");
print(mapper);
sqlSession.commit();
System.out.println("增加成功");
//删除
mapper.deleteDept(12);
print(mapper);
sqlSession.commit();
System.out.println("删除成功");
//修改
mapper.updateDept(2, "熊10", 23, "男", "萍乡");
print(mapper);
sqlSession.commit();
System.out.println("修改成功");
sqlSession.close();
}
}
可以看到运行结果为: