如何使用 Mybatis 实现数据库 CURD 操作?
作者 | 阿文,责编 | 郭芮
头图 | CSDN 下载自东方IC
出品 | CSDN(ID:CSDNnews)
准备工作
idea maven mysql
创建数据库并插入数据
mysql> create database mybatis_db;
Query OK, 1 row affected (0.01 sec)
mysql> use mybatis_db;
Database changed
mysql> create table t_user(
-> id int(32) primary key auto_increment,
-> username varchar(50),
-> jobs varchar(50),
-> phone varchar(16));
Query OK, 0 rows affected, 1 warning (0.01 sec)
mysql> insert into t_user values(1,"zhangsan","teacher","13142767333");
Query OK, 1 row affected (0.01 sec)
mysql> insert into t_user values(2,"lisi","engineer","13142767334");
Query OK, 1 row affected (0.01 sec)
mysql> insert into t_user values(3,"wangwu","pilot","12342767334");
Query OK, 1 row affected (0.00 sec)
mysql>
配置pom.xml 下载jar包
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
配置mybatis-config
src\main
目录点击右键创建一个目录,创建的时候选择resource即可),内容如下,具体不需要过多解释,该配置文件主要是定义JDBC相关的参数包括使用的驱动、mysql 访问地址、用户名和密码以及通过mappers 定义一个mybatis 的映射文件。<?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="mysql">
<environment id="mysql">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://192.168.10.128:3306/mybatis_db" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml" />
</mappers>
</configuration>
创建user类
package com.mybatis;
public class User {
private Integer id;
private String username;
private String jobs;
private String phone;
public Integer getId() {
return id;
}
public String getUsername() {
return username;
}
public String getJobs() {
return jobs;
}
public String getPhone() {
return phone;
}
public void setId(Integer id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setJobs(String jobs) {
this.jobs = jobs;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", jobs='" + jobs + '\'' +
", phone='" + phone + '\'' +
'}';
}
}
创建测试类
<?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="UserMapper">
<!--根据用户编号获取用户信息 -->
<select id="findUserById" parameterType="Integer" resultType="com.mybatis.User">
select * from t_user where id=#{id}
</select>
</mapper>
package com.mybatis;
import java.io.InputStream;
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 org.junit.jupiter.api.Test;
/**
* @Auth: xxxx
* @E-mail: xxx
* @title: MybatisTest
* @projectName: mybatis
* @description: TODO 描述信息
* @Date 2020/4/7 9:15 下午
**/
public class MybatisTest {
@Test
public void findUserByIdTest() throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = sqlSession.selectOne("findUserById", 1);
System.out.println(user.toString());
sqlSession.close();
}
}
<select id="findUserByName" parameterType="String" resultType="com.mybatisdemo.User">
select * from t_user where username like concat('%','${value}','%')
</select>
@Test
public void findUserByNameTest() throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
List<User> users = sqlSession.selectList("findUserByName","g");
for (User user:users){
System.out.println(user.toString());
}
sqlSession.close();
}
<insert id="addUser" parameterType="com.mybatisdemo.User" >
insert into t_user(username,jobs,phone) value (#{username},#{jobs},#{phone})
</insert>
@Test
public void addUser() throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User();
user.setUsername("beiluo");
user.setJobs("DevOps");
user.setPhone("1314566666");
int rows = sqlSession.insert("addUser",user);
if (rows >0){
System.out.println("Success add "+ rows +"data!");
}else{
System.out.println("add data fail!");
}
sqlSession.commit();
sqlSession.close();
}
<update id="updateUserInfo" parameterType="com.mybatisdemo.User">
update t_user set username=#{username},jobs=#{jobs},phone=#{phone} where id =#{id}
</update>
@Test
public void updateUserinfo() throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User();
user.setId(1);
user.setUsername("jike");
user.setJobs("qa");
user.setPhone("13142764432");
int rows = sqlSession.update("updateUserInfo",user);
if (rows >0){
System.out.println("Success update "+ rows +" data!");
}else{
System.out.println("update data fail!");
}
sqlSession.commit();
sqlSession.close();
}
<delete id="deleteUser" parameterType="com.mybatisdemo.User" >
delete from t_user where id=#{id}
</delete>
@Test
public void deleteUser() throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
int rows = sqlSession.delete("deleteUser",1);
if (rows >0){
System.out.println("Success delete "+ rows +" data!");
}else{
System.out.println("delete data fail!");
}
sqlSession.commit();
sqlSession.close();
}
关注公众号:拾黑(shiheibook)了解更多
[广告]赞助链接:
四季很好,只要有你,文娱排行榜:https://www.yaopaiming.com/
让资讯触达的更精准有趣:https://www.0xu.cn/
关注网络尖刀微信公众号
随时掌握互联网精彩
随时掌握互联网精彩
赞助链接
排名
热点
搜索指数
- 1 准确把握守正创新的辩证关系 7935823
- 2 中国黄金原董事长家搜出大量黄金 7949933
- 3 空调英文不会男生盯着考场空调看 7833200
- 4 消费品以旧换新“加速度” 7795408
- 5 被铁路售票员的手速惊到了 7614475
- 6 网红赤木刚宪爆改赵露思 7564825
- 7 县委原书记大搞“刷白墙”被通报 7444153
- 8 山姆代购在厕所分装蛋糕 7378578
- 9 马龙刘诗雯穿正装打混双 7247405
- 10 刘强东提前发年终奖 7198566