mybatis項(xiàng)目CRUD步驟實(shí)例詳解
mybatis項(xiàng)目CRUD步驟
1.pom.xml引入相應(yīng)的依賴(lài)
<?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)入依賴(lài)-->
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!-- 導(dǎo)入lombok依賴(lài)-->
<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目錄下寫(xiě)配置文件
- 數(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>
<!-- 開(kāi)啟日志-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!--顯示的開(kāi)啟緩存-->
<setting name="cacheEnabled" value="true"/>
</settings>
<!-- 類(lèi)型別名:可以給實(shí)體類(lèi)起別名-->
<typeAliases>
<!-- 固定別名-->
<!-- <typeAlias type="com.wyc.pojo.User" alias="User"></typeAlias>-->
<!-- 掃描包:掃描實(shí)體類(lèi)的包,它的默認(rèn)別名就為這個(gè)類(lèi)的類(lèi)名,首字母小寫(xiě)!-->
<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í)體類(lèi),類(lèi)名與數(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層編寫(xiě)Mapper接口,和Mapper.xml sql語(yǔ)法
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中開(kāi)啟二級(jí)緩存-->
<cache eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"
></cache>
<!--自定義緩存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
<!--useCache="true":使用開(kāi)啟緩存-->
<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語(yǔ)句
<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語(yǔ)句
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è)萬(wàn)能的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語(yǔ)句
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.編寫(xiě)測(cè)試類(lèi)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
//查詢(xún)所有用戶(hù)
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查詢(xún)
public void test1(){
SqlSession sqlSession = MybayisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User userById = mapper.getUserById(1);
System.out.println(userById);
}
@Test
//添加用戶(hù) 增刪改查需要提交事物
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
//修改用戶(hù)
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
//刪除用戶(hù)
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("狂神說(shuō)");
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","狂神說(shuō)");
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","超哥說(shuō)");
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如何靜態(tài)加載@configurationProperties
這篇文章主要介紹了springboot如何靜態(tài)加載@configurationProperties,本文一個(gè)錯(cuò)誤案例和成功案例結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-07-07
SpringBoot解析JSON數(shù)據(jù)的三種方案
JSON(JavaScript Object Notation) 是一種輕量級(jí)的數(shù)據(jù)交換格式,易于人閱讀和編寫(xiě),同時(shí)也易于機(jī)器解析和生成,本文給大家介紹了SpringBoot解析JSON數(shù)據(jù)的三種方案,需要的朋友可以參考下2024-03-03
Java長(zhǎng)字符串加密的實(shí)現(xiàn)
在Java中,字符串是一種常見(jiàn)的數(shù)據(jù)類(lèi)型,我們經(jīng)常需要對(duì)其進(jìn)行加密和解密,本文主要介紹了Java長(zhǎng)字符串加密的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2024-02-02
Android中PreferenceFragment的使用詳解
本文主要介紹了Android中PreferenceFragment的使用詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
圖解Springboot集成七牛云并實(shí)現(xiàn)圖片上傳功能過(guò)程
在實(shí)際開(kāi)發(fā)中 ,基本都會(huì)有應(yīng)用到文件上傳的場(chǎng)景,但隨著或多或少的需求問(wèn)題,之前有在springboot上用過(guò)七牛云實(shí)現(xiàn)圖片上傳,今天因?yàn)槟承┰蛴种匦率褂昧讼缕吲T埔虼讼肟偨Y(jié)下七牛云2021-11-11
SpringBoot項(xiàng)目訪問(wèn)任意接口出現(xiàn)401錯(cuò)誤的解決方案
今天小編就為大家分享一篇關(guān)于SpringBoot項(xiàng)目訪問(wèn)任意接口出現(xiàn)401錯(cuò)誤的解決方案,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-01-01
JDK1.8中ConcurrentHashMap中computeIfAbsent死循環(huán)bug問(wèn)題
這篇文章主要介紹了JDK1.8中ConcurrentHashMap中computeIfAbsent死循環(huán)bug,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08
詳解spring開(kāi)發(fā)_JDBC操作MySQL數(shù)據(jù)庫(kù)
本篇文章主要介紹了spring開(kāi)發(fā)_JDBC操作MySQL數(shù)據(jù)庫(kù),具有一定的參考價(jià)值,有興趣的可以了解一下。2016-12-12
Java?實(shí)戰(zhàn)范例之校園二手市場(chǎng)系統(tǒng)的實(shí)現(xiàn)
讀萬(wàn)卷書(shū)不如行萬(wàn)里路,只學(xué)書(shū)上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實(shí)戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SSM+mysql+maven+tomcat實(shí)現(xiàn)一個(gè)校園二手市場(chǎng)系統(tǒng),大家可以在過(guò)程中查缺補(bǔ)漏,提升水平2021-11-11

