春ブーツ(2):データベースのMyBatisの操作

(1)MySQLデータシート製剤

まず、次のようにニュースのテーブルの構造は、表には、次のとおりです。


4824974-cc14132c8fc97e06.jpg
画像

コンテンツデータの表は以下のとおりです。


4824974-905e40d977440e43.jpg
画像

2.関連

2.1ポンポン設定ファイル

春ブーツの積分MyBatisの、のpom.xml(Mavenプロジェクト)を変更する必要性に起因して、MySQLの設定でMyBatisのを追加します。

vscodeでは、pom.xmlファイルを選択し、右クリックして、選択した編集スタータ

4824974-0e5638ed8bbc14e5.jpg
画像

同じ時間チェックmysqlの、MyBatisのオプションを入力します。


4824974-83d6779348fcd70a.jpg
画像

更新後、二つ以上に依存するオプションでのpom.xml:

<dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>2.0.1</version>
      <scope>compile</scope>
    </dependency>

2.2設定オプションapplication.properties

接続文字列application.properties設定ファイルになどのデータベース・アカウント、パスワードを、塗りつぶしです。

#application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/zlfj?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=${你的数据库密码}
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

2.3エンティティクラスを作成します

プロジェクトファイルのディレクトリを以下に示します。


4824974-2ad384547cd07cbd.jpg
画像

newsentityクラスを作成し、SQLテーブルを持つJavaファイルをマッピングするために使用されます。

//NewsEntity.java
public class NewsEntity implements Serializable{
    private static final long serialVersionUID = 1L;

    private Long id;
    
    private String title;
    
    private String content;
    
    private Date gmttime;
    /*
    **省略getset 方法,记得写
    */
}

2.4ダオ層を作成すると、特定のデータ操作を定義します

(1)注釈スタイルを使用して

DAO NewsDao.javaは、データベース操作を実施するために注釈層及び書き込み処理に定義されています。

@Mapper
public interface NewsDao{

    /**
    * 查询单个
    * @return
    */
    @Select("SELECT * from news WHERE id=#{id}")
    NewsEntity queryObject(@Param("id") Long id);
}

エンティティがクラスに渡された場合は、マップを注釈付きの結果を照会する必要があります。

 /**
    * 保存
    * @return
    */
    @Results(
        {
        @Result(property = "id", column = "id", id = true), 
        @Result(property = "title", column = "title"),
        @Result(property = "content", column = "content"), 
        @Result(property = "gmttime", column = "gmtTime") 
        }
        )
    @Insert("insert into news (title,content,gmtTime) values(#{title},#{content},#{gmttime})")
    void save(NewsEntity news);
    
    
    /**
    * 修改
    * @return
    */
    @Results(
        {
        @Result(property = "id", column = "id", id = true), 
        @Result(property = "title", column = "title"),
        @Result(property = "content", column = "content"), 
        @Result(property = "gmttime", column = "gmtTime") 
        }
        )
    @Update("update news set `title`=#{title},`content`=#{content},`gmtTime`=#{gmttime} where id=#{id}")
    void update(NewsEntity news);

(2)XMLの方法を使用して

注釈マッパーDAOを添加しながら第一各動作のDAO層を定義します。

package com.zhb.nongboot.dao;


import java.util.List;
import java.util.Map;

import com.zhb.nongboot.entity.NewsEntity;

import org.apache.ibatis.annotations.Mapper;


@Mapper
public interface NewsDao{
    

     /**
    * 查询
    * @return
    */
    NewsEntity queryObject(Long id);

    /**
    * 查询列表
    * @return
    */
    List<NewsEntity> queryList(Map<String, Object> map);

    /**
    * 查询总数
    * @return
    */
    int queryTotal(Map<String, Object> map);

    /**
    * 保存
    * @return
    */
    void save(NewsEntity news);

    /**
    * 修改
    * @return
    */
    void update(NewsEntity news);

    /**
    * 删除
    * @return
    */
    void delete(Long id);  
}

同じディレクトリにNewsDao.java、新しいNewsDao.xmlファイルは、その特定のSQLデータベースの操作を定義します。

<?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.zhb.nongboot.dao.NewsDao">

    <resultMap id="newsMap" type="com.zhb.nongboot.entity.NewsEntity">
        <result property="id" column="id"/>
        <result property="title" column="title"/>
        <result property="content" column="content"/>
        <result property="gmttime" column="gmtTime"/>
    </resultMap>
    <select id="queryObject" resultType="com.zhb.nongboot.entity.NewsEntity">
        select * from news where id = #{value}
    </select>

    <select id="queryList" resultType="com.zhb.nongboot.entity.NewsEntity">
        select * from news where 1=1

        <choose>
            <when test="sidx != null and sidx.trim() != ''">
                order by ${sidx} ${order}
            </when>
            <otherwise>
                order by id desc
            </otherwise>
        </choose>
        <if test="offset != null and limit != null">
            limit #{offset}, #{limit}
        </if>
    </select>

    <select id="queryTotal" resultType="int">
        select count(*) from news where 1=1

    </select>

    <insert id="save" parameterType="com.zhb.nongboot.entity.NewsEntity" useGeneratedKeys="true" keyProperty="id">
        insert into news
        (
        `title`,
        `content`,
        `gmtTime`
        )
        values
        (
        #{title},
        #{content},
        #{gmttime}
        )
    </insert>

    <update id="update" parameterType="com.zhb.nongboot.entity.NewsEntity">
        update news
        <set>
            <if test="title != null">`title` = #{title},</if>
            <if test="content != null">`content` = #{content},</if>
            <if test="gmttime != null">`gmtTime` = #{gmttime}</if>
        </set>
        where id = #{id}
    </update>

    <delete id="delete">
        delete from news where id = #{value}
    </delete>

    <delete id="deleteBatch">
        delete from news where id in
        <foreach item="id" collection="array" open="(" separator="," close=")">
            #{id}
        </foreach>
    </delete>

</mapper>

2.5方法と定義されたサービスレイヤインタフェース(特にサービス論理層)を実装

ここでは、ニュースの操作このテーブルへの追加や削除されているので、そのインタフェース定義:

NewsService.java
import java.util.List;
import java.util.Map;

import com.zhb.nongboot.entity.NewsEntity;

import org.springframework.stereotype.Service;


public interface NewsService{
    

     /**
    * 查询
    * @return
    */
    NewsEntity queryObject(Long id);

    /**
    * 查询列表
    * @return
    */
    List<NewsEntity> queryList(Map<String, Object> map);

    /**
    * 查询总数
    * @return
    */
    int queryTotal(Map<String, Object> map);

    /**
    * 保存
    * @return
    */
    void save(NewsEntity news);

    /**
    * 修改
    * @return
    */
    void update(NewsEntity news);

    /**
    * 删除
    * @return
    */
    void delete(Long id);

   
}

サービスの具体的な実現:

//NewsServiceImpl.java

package com.zhb.nongboot.service.impl;

import java.util.List;
import java.util.Map;

import com.zhb.nongboot.dao.NewsDao;
import com.zhb.nongboot.entity.NewsEntity;
import com.zhb.nongboot.service.NewsService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class NewsServiceImpl implements NewsService{

    @Autowired
    private NewsDao newsDao;

        
    @Override
    public NewsEntity queryObject(Long id){
            NewsEntity entity = newsDao.queryObject(id);

                                                    
        return entity;
    }
    
    @Override
    public List<NewsEntity> queryList(Map<String, Object> map){
        List<NewsEntity> list = newsDao.queryList(map);
        return list;
    }
        

    
    
    @Override
    public int queryTotal(Map<String, Object> map){
        return newsDao.queryTotal(map);
    }
    
    @Override
    public void save(NewsEntity news){
        newsDao.save(news);
    }
    
    @Override
    public void update(NewsEntity news){
        newsDao.update(news);
    }
    
    @Override
    public void delete(Long id){
        newsDao.delete(id);
    }
    
}

注意:ここではそのコンテナ(コントロールのIOC反転)の春の統一管理を手渡し、春には、この春NewsServiceは、登録したい、サービスを定義しているので

だから、パブリック・クラスは、コメントを追加することを忘れないでNewsServiceはNewsServiceImplを定義し実装し@Service

@Service
public class NewsServiceImpl implements NewsService{

そうでなければ、春には、そのサービスを見つけることができません文句を言うだろう。

2.6controller層:登録ルートの受信パラメータと

簡単な保存方法が正常であるとここでは、queryメソッドをテストします。

import java.util.Date;
import java.util.HashMap;

import com.zhb.nongboot.entity.NewsEntity;
import com.zhb.nongboot.service.NewsService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("news")
public class NewsController {

    @Autowired
    private NewsService newsService;
    
    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public NewsEntity info(@PathVariable("id") Long id){
        NewsEntity news = newsService.queryObject(id);
       return news;
    }

    @RequestMapping("save/{name}")
    public HashMap<String,String> save(@PathVariable("name") String name){
        NewsEntity news = new NewsEntity();
        news.setTitle(name);
        news.setContent("新增通知成功");
        news.setGmttime(new Date());
        newsService.save(news);
        return (HashMap<String, String>) new HashMap<>().put("message", "ok");
    }
    

/ニュースにアクセスする場合/情報/ 2は、表2のニュースの行のIDを返します。

/ニュース/保存/ titlename時間にアクセスすると、レコードtitlenameにタイトルを追加します。

テスト:

単一行の問合せレコード:


4824974-7de63304a93bb249.jpg
画像

保存


4824974-390646b35e5840f3.jpg
画像

4824974-57d6c9eccdd335de.jpg
画像

テストは成功です。

おすすめ

転載: blog.csdn.net/weixin_33851604/article/details/91023204