最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

mybatis項目CRUD步驟實例詳解

 更新時間:2022年09月29日 10:04:48   作者:super-broo  
這篇文章主要介紹了mybatis項目CRUD步驟,包括pom.xml引入相應(yīng)的依賴,在resources目錄下寫配置文件,本文結(jié)合實例代碼給大家介紹的非常詳細,需要的朋友可以參考下

mybatis項目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ù)庫連接配置
  • 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. 創(chuàng)建相應(yīng)的包

img

各個層的含義

img

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層創(chuàng)建實體類,類名與數(shù)據(jù)庫表一致

  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

img

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)在傳入一個萬能的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();
          //執(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如此簡單");
          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("微服務(wù)如此簡單");
          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);
      }
  }

到此這篇關(guān)于mybatis項目CRUD步驟的文章就介紹到這了,更多相關(guān)mybatis CRUD步驟內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 利用Java巧妙解決Excel公式迭代計算

    利用Java巧妙解決Excel公式迭代計算

    迭代計算其實是在?Excel?中,一種公式的循環(huán)引用,那么如何利用Java語言巧妙解決Excel公式迭代計算的問題呢,下面小編就來和大家詳細講講吧
    2023-10-10
  • 利用SpringBoot實現(xiàn)多數(shù)據(jù)源的兩種方式總結(jié)

    利用SpringBoot實現(xiàn)多數(shù)據(jù)源的兩種方式總結(jié)

    關(guān)于動態(tài)數(shù)據(jù)源的切換的方案有很多,核心只有兩種,一種是構(gòu)建多套環(huán)境,另一種是基于spring原生的AbstractRoutingDataSource切換,這篇文章主要給大家介紹了關(guān)于利用SpringBoot實現(xiàn)多數(shù)據(jù)源的兩種方式,需要的朋友可以參考下
    2021-10-10
  • Java 深入探討設(shè)計模式之原型模式篇

    Java 深入探討設(shè)計模式之原型模式篇

    設(shè)計模式(Design pattern)是一套被反復(fù)使用、多數(shù)人知曉的、經(jīng)過分類編目的、代碼設(shè)計經(jīng)驗的總結(jié)。使用設(shè)計模式是為了可重用代碼、讓代碼更容易被他人理解、保證代碼可靠性
    2021-10-10
  • MultipartFile中transferTo(File file)的路徑問題及解決

    MultipartFile中transferTo(File file)的路徑問題及解決

    這篇文章主要介紹了MultipartFile中transferTo(File file)的路徑問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • Java中實現(xiàn)在一個方法中調(diào)用另一個方法

    Java中實現(xiàn)在一個方法中調(diào)用另一個方法

    下面小編就為大家分享一篇Java中實現(xiàn)在一個方法中調(diào)用另一個方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-02-02
  • jxl操作excel寫入數(shù)據(jù)不覆蓋原有數(shù)據(jù)示例

    jxl操作excel寫入數(shù)據(jù)不覆蓋原有數(shù)據(jù)示例

    網(wǎng)上很多例子,都是用Jxl讀或者寫excel,本文實現(xiàn)的功能就是將數(shù)據(jù)源in.xls的第幾行第幾列數(shù)據(jù)寫入到out.xls的第幾行第幾列,不覆蓋out.xls其他原有的數(shù)據(jù)。
    2014-03-03
  • Javaweb resin4如何配置端口虛擬目錄

    Javaweb resin4如何配置端口虛擬目錄

    這篇文章主要介紹了Javaweb resin4如何配置端口虛擬目錄,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-07-07
  • 動態(tài)更改Spring定時任務(wù)Cron表達式的優(yōu)雅方案實例詳解

    動態(tài)更改Spring定時任務(wù)Cron表達式的優(yōu)雅方案實例詳解

    spring定時器非常強大,但是有時候我們需要在不需要重啟應(yīng)用就可以動態(tài)的改變Cron表達式的值,下面這篇文章主要給大家介紹了關(guān)于動態(tài)更改Spring定時任務(wù)Cron表達式的優(yōu)雅方案,需要的朋友可以參考下
    2022-12-12
  • Spring?Boot集成JasperReport生成文檔的方法

    Spring?Boot集成JasperReport生成文檔的方法

    由于工作需要,要實現(xiàn)后端根據(jù)模板動態(tài)填充數(shù)據(jù)生成PDF文檔,通過技術(shù)選型,使用Ireport5.6來設(shè)計模板,結(jié)合JasperReports5.6工具庫來調(diào)用渲染生成PDF文檔,這篇文章主要介紹了Spring?Boot集成JasperReport生成文檔,需要的朋友可以參考下
    2023-09-09
  • java web學(xué)習(xí)_淺談request對象中g(shù)et和post的差異

    java web學(xué)習(xí)_淺談request對象中g(shù)et和post的差異

    下面小編就為大家?guī)硪黄猨ava web學(xué)習(xí)_淺談request對象中g(shù)et和post的差異。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-05-05

最新評論

呼玛县| 安阳县| 来凤县| 辽宁省| 文化| 乐陵市| 中超| 正蓝旗| 安溪县| 班戈县| 应用必备| 岱山县| 邵阳市| 武定县| 江津市| 日喀则市| 通辽市| 商洛市| 萨迦县| 宝鸡市| 紫金县| 庆安县| 伊宁县| 汉寿县| 河曲县| 安宁市| 湖州市| 多伦县| 灵川县| 赤城县| 高要市| 新源县| 镇赉县| 义马市| 区。| 蕉岭县| 台东市| 永川市| 和硕县| 达州市| 巴楚县|