mybatis项目CRUD步骤实例详解
作者:super-broo 时间:2023-04-21 13:12:00
mybatis项目CRUD步骤
1.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>org.example</groupId>
<artifactId>demo1</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>demo01</module>
<module>demo02</module>
<module>demo03</module>
<module>demo04</module>
</modules>
<!-- 导入依赖-->
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!-- 导入lombok依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
</dependencies>
<!--maven资源导出,约定大于配置-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties
</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties
</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
2. 在resources目录下写配置文件
数据库连接配置
db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
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核心配置文件-->
<configuration>
<!-- 引入外部配置文件-->
<properties resource="db.properties">
</properties>
<settings>
<!-- 开启日志-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!--显示的开启缓存-->
<setting name="cacheEnabled" value="true"/>
</settings>
<!-- 类型别名:可以给实体类起别名-->
<typeAliases>
<!-- 固定别名-->
<!-- <typeAlias type="com.wyc.pojo.User" alias="User"></typeAlias>-->
<!-- 扫描包:扫描实体类的包,它的默认别名就为这个类的类名,首字母小写!-->
<package name="com.wyc.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!-- 注册mapper-->
<mappers>
<mapper class="com.wyc.dao.UserMapper"/>
</mappers>
</configuration>
自定义缓存配置
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="./tmpdir/Tmp_EhCache"/>
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<cache
name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
3. 创建相应的包
各个层的含义
4. 在utils层
获取获取sqlSessionFactory对象
package com.wyc.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 MybayisUtils {
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();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
}
5. 在pojo层创建实体类,类名与数据库表一致
package com.wyc.pojo;
import lombok.Data;
@Data //自动生成get set 等方法,详细点击 右边的Structure
public class User {
private int id;
private String name;
private String pwd;
}
6.在dao层编写Mapper接口,和Mapper.xml sql语法
UserMapper
package com.wyc.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 MybayisUtils {
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();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
}
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">
<mapper namespace="com.wyc.dao.UserMapper">
<insert id="add">
</insert>
<insert id="addUser" parameterType="com.wyc.pojo.User">
insert into mybatis.user (id,name,pwd) value (#{id},#{name},#{pwd})
</insert>
<insert id="addUser2" parameterType="map">
insert into mybatis.user (id,name,pwd) value (#{userid},#{username},#{userpwd})
</insert>
<update id="update" parameterType="com.wyc.pojo.User">
update mybatis.user set name =#{name},pwd=#{pwd} where id = #{id} ;
</update>
<delete id="deleteUser">
delete from mybatis.user where id = #{id}
</delete>
<select id="getUserList" resultType="com.wyc.pojo.User">
select * from mybatis.user
</select>
<select id="getUserById" resultType="com.wyc.pojo.User" parameterType="int">
select * from mybatis.user where id = #{id}
</select>
<select id="getUserById2" resultType="com.wyc.pojo.User" parameterType="map">
select * from mybatis.user where id = #{id} and name = #{name};
</select>
<select id="getUserLike" resultType="com.wyc.pojo.User">
select * from mybatis.user where name like "%"#{value}"%"
</select>
<!-- 在当前mapper.xml中开启二级缓存-->
<cache eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"
></cache>
<!--自定义缓存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
<!--useCache="true":使用开启缓存-->
<select id="queryUserById" parameterType="int" resultType="user" useCache="true">
select * from mybatis.user where id = #{id}
</select>
</mapper>
BlogMapper
BlogMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wyc.dao.BlogMapper">
<insert id="addBlog" parameterType="blog">
insert into mybatis.blog (id,title,author,create_time,views)
value (#{id},#{title},#{author},#{createTime},#{views});
</insert>
<sql id="if-title-author"> //if语句
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from mybatis.blog where 1=1
<where>
<include refid="if-title-author"></include>
</where>
</select>
<select id="queryBlogChoose" parameterType="map" resultType="blog"> //choose语句
select * from mybatis.blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="title != null">
and author = #{author}
</when>
<otherwise>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
<!--我们现在传入一个万能的map,这个map可以存一个集合
select * from mybatis.blog where 1=1 and (id=1 or id=2 or id=3)
-->
<select id="queryBlogForeach" parameterType="map" resultType="blog"> //foreach语句
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or"> separator 拼接sql
id = #{id}
</foreach>
</where>
</select>
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</set>
where id = #{id}
</update>
</mapper>
7.编写测试类test,进行测试
1. UserTest
package com.wyc.dao;
import com.wyc.pojo.User;
import com.wyc.utils.MybayisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class UserDaoTest {
@Test
//查询所有用户
public void test(){
//第一步:获得SqlSession对象
SqlSession sqlSession = MybayisUtils.getSqlSession();
//执行sql 方式一:getMapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
}
@Test
public void testlike(){
SqlSession sqlSession = MybayisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userLike = mapper.getUserLike("zhang%"); //%最好在sql中拼接
for (User user : userLike) {
System.out.println("______________________");
System.out.println(user);
}
}
@Test
//根据id查询
public void test1(){
SqlSession sqlSession = MybayisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User userById = mapper.getUserById(1);
System.out.println(userById);
}
@Test
//添加用户 增删改查需要提交事物
public void test2(){
SqlSession sqlSession = MybayisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int addUser = mapper.addUser(new User(5,"HH","123"));
sqlSession.commit();
}
@Test
public void add(){
SqlSession sqlSession = MybayisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("userid",7);
map.put("username","zhangsan");
mapper.addUser2(map);
sqlSession.commit();
}
@Test
//修改用户
public void test3(){
SqlSession sqlSession = MybayisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int update = mapper.update(new User(3, "rr", "1234"));
sqlSession.commit();
}
@Test
//删除用户
public void test4(){
SqlSession sqlSession = MybayisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int user = mapper.deleteUser(2);
sqlSession.commit();
}
}
2. BlogTest
import com.wyc.dao.BlogMapper;
import com.wyc.dao.UserMapper;
import com.wyc.pojo.Blog;
import com.wyc.pojo.User;
import com.wyc.utils.IDutils;
import com.wyc.utils.MybayisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class MyTest {
@Test
public void test(){
SqlSession sqlSession = MybayisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDutils.getId());
blog.setTitle("mybatis如此简单");
blog.setAuthor("狂神说");
blog.setCreateTime(new Date());
blog.setViews(9999);
mapper.addBlog(blog);
blog.setId(IDutils.getId());
blog.setTitle("java如此简单");
mapper.addBlog(blog);
blog.setId(IDutils.getId());
blog.setTitle("spring如此简单");
mapper.addBlog(blog);
blog.setId(IDutils.getId());
blog.setTitle("微服务如此简单");
mapper.addBlog(blog);
sqlSession.commit();
}
@Test
public void test2(){
SqlSession sqlSession = MybayisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("author","狂神说");
List<Blog> blogs = mapper.queryBlogIf(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
}
@Test
public void test3(){
SqlSession sqlSession = MybayisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("views",9999);
List<Blog> blogs = mapper.queryBlogChoose(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
}
@Test
public void test4(){
SqlSession sqlSession = MybayisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
// map.put("views",9999);
map.put("id","aaee3fee53d041ef93f51ff42d432d");
map.put("author","超哥说");
map.put("title","编程如此简单");
mapper.updateBlog(map);
sqlSession.commit();
}
@Test
public void test5(){
SqlSession sqlSession = MybayisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
ArrayList<Integer> ids = new ArrayList<Integer>();
ids.add(1);
map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.commit();
}
@Test
public void queryUserById(){
SqlSession sqlSession = MybayisUtils.getSqlSession();
SqlSession sqlSession2 = MybayisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.queryUserById(1);
System.out.println(user);
sqlSession.close();
UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
User user2 = mapper2.queryUserById(1);
System.out.println(user2);
}
}
来源:https://blog.csdn.net/qq_45903007/article/details/126685597
标签:mybatis,CRUD
0
投稿
猜你喜欢
C#适配器模式的使用
2022-02-05 15:47:21
Java 队列实现原理及简单实现代码
2021-07-19 05:12:56
c++与c#的时间转换示例分享
2022-08-22 07:21:40
C#实现Check Password和锁定输错密码锁定账户功能
2023-01-20 03:04:33
如何使用Java redis实现发送手机验证码功能
2023-11-26 17:25:00
Mybatis实现增删改查(CRUD)实例代码
2022-10-05 20:03:22
Java中String类常用方法总结详解
2022-03-06 04:50:58
SpringBoot使用AOP+注解实现简单的权限验证的方法
2022-07-29 00:59:09
基于selenium-java封装chrome、firefox、phantomjs实现爬虫
2022-04-07 19:04:28
Mybatis Plus 中的LambdaQueryWrapper示例详解
2023-03-26 04:52:06
C# 重写Notification提示窗口的示例代码
2021-12-26 19:57:59
springboot整合quartz项目使用案例
2023-02-13 19:57:12
SpringBoot整合BCrypt实现密码加密
2021-12-09 20:01:08
一文带你全面了解Java Hashtable
2021-09-19 01:39:39
Android使用Retrofit上传文件功能
2022-08-28 08:42:38
C#多线程系列之任务基础(一)
2022-12-09 04:48:22
Java详细讲解堆排序与时间复杂度的概念
2023-10-20 02:00:11
C# StreamReader类实现读取文件的方法
2023-06-20 13:02:00
OpenGL Shader实现阴影遮罩效果
2022-04-23 19:38:02
Java中抽象类与方法的重写方式
2023-08-25 09:20:29