mybatis項(xiàng)目CRUD步驟實(shí)例詳解
mybatis項(xiàng)目CRUD步驟
1.pom.xml引入相應(yīng)的依賴
<?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>
<!-- 導(dǎo)入依賴-->
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!-- 導(dǎo)入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資源導(dǎo)出,約定大于配置-->
<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目錄下寫配置文件
- 數(shù)據(jù)庫(kù)連接配置
- 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>
<!-- 類型別名:可以給實(shí)體類起別名-->
<typeAliases>
<!-- 固定別名-->
<!-- <typeAlias type="com.wyc.pojo.User" alias="User"></typeAlias>-->
<!-- 掃描包:掃描實(shí)體類的包,它的默認(rèn)別名就為這個(gè)類的類名,首字母小寫!-->
<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>
<!-- 注冊(cè)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. 創(chuàng)建相應(yīng)的包

各個(gè)層的含義

4. 在utils層
獲取獲取sqlSessionFactory對(duì)象
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對(duì)象
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層創(chuàng)建實(shí)體類,類名與數(shù)據(jù)庫(kù)表一致
package com.wyc.pojo;
import lombok.Data;
@Data //自動(dòng)生成get set 等方法,詳細(xì)點(diǎn)擊 右邊的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對(duì)象
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>
<!-- 在當(dāng)前mapper.xml中開啟二級(jí)緩存-->
<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>
<!--我們現(xiàn)在傳入一個(gè)萬能的map,這個(gè)map可以存一個(gè)集合
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.編寫測(cè)試類test,進(jìn)行測(cè)試
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對(duì)象
SqlSession sqlSession = MybayisUtils.getSqlSession();
//執(zhí)行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
//根據(jù)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如此簡(jiǎn)單");
blog.setAuthor("狂神說");
blog.setCreateTime(new Date());
blog.setViews(9999);
mapper.addBlog(blog);
blog.setId(IDutils.getId());
blog.setTitle("java如此簡(jiǎn)單");
mapper.addBlog(blog);
blog.setId(IDutils.getId());
blog.setTitle("spring如此簡(jiǎn)單");
mapper.addBlog(blog);
blog.setId(IDutils.getId());
blog.setTitle("微服務(wù)如此簡(jiǎn)單");
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","編程如此簡(jiǎn)單");
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);
}
}
到此這篇關(guān)于mybatis項(xiàng)目CRUD步驟的文章就介紹到這了,更多相關(guān)mybatis CRUD步驟內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
利用SpringBoot實(shí)現(xiàn)多數(shù)據(jù)源的兩種方式總結(jié)
關(guān)于動(dòng)態(tài)數(shù)據(jù)源的切換的方案有很多,核心只有兩種,一種是構(gòu)建多套環(huán)境,另一種是基于spring原生的AbstractRoutingDataSource切換,這篇文章主要給大家介紹了關(guān)于利用SpringBoot實(shí)現(xiàn)多數(shù)據(jù)源的兩種方式,需要的朋友可以參考下2021-10-10
MultipartFile中transferTo(File file)的路徑問題及解決
這篇文章主要介紹了MultipartFile中transferTo(File file)的路徑問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
Java中實(shí)現(xiàn)在一個(gè)方法中調(diào)用另一個(gè)方法
下面小編就為大家分享一篇Java中實(shí)現(xiàn)在一個(gè)方法中調(diào)用另一個(gè)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-02-02
jxl操作excel寫入數(shù)據(jù)不覆蓋原有數(shù)據(jù)示例
網(wǎng)上很多例子,都是用Jxl讀或者寫excel,本文實(shí)現(xiàn)的功能就是將數(shù)據(jù)源in.xls的第幾行第幾列數(shù)據(jù)寫入到out.xls的第幾行第幾列,不覆蓋out.xls其他原有的數(shù)據(jù)。2014-03-03
動(dòng)態(tài)更改Spring定時(shí)任務(wù)Cron表達(dá)式的優(yōu)雅方案實(shí)例詳解
spring定時(shí)器非常強(qiáng)大,但是有時(shí)候我們需要在不需要重啟應(yīng)用就可以動(dòng)態(tài)的改變Cron表達(dá)式的值,下面這篇文章主要給大家介紹了關(guān)于動(dòng)態(tài)更改Spring定時(shí)任務(wù)Cron表達(dá)式的優(yōu)雅方案,需要的朋友可以參考下2022-12-12
Spring?Boot集成JasperReport生成文檔的方法
由于工作需要,要實(shí)現(xiàn)后端根據(jù)模板動(dòng)態(tài)填充數(shù)據(jù)生成PDF文檔,通過技術(shù)選型,使用Ireport5.6來設(shè)計(jì)模板,結(jié)合JasperReports5.6工具庫(kù)來調(diào)用渲染生成PDF文檔,這篇文章主要介紹了Spring?Boot集成JasperReport生成文檔,需要的朋友可以參考下2023-09-09
java web學(xué)習(xí)_淺談request對(duì)象中g(shù)et和post的差異
下面小編就為大家?guī)硪黄猨ava web學(xué)習(xí)_淺談request對(duì)象中g(shù)et和post的差異。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-05-05

