目录
- mybatis项目CRUD步骤
- 1.pom.xml引入相应的依赖
- 2. 在resources目录下写配置文件
- 3. 创建相应的包
- 4. 在utils层
- 5. 在pojo层创建实体类,类名与数据库表一致
- 6.在dao层编写Mapper接口,和Mapper.xml sql语法
- 7.编写测试类test,进行测试
- 1. UserTest
- 2. BlogTest
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);
}
}