spring boot (two): Mybatis operation of the database

(1) mysql Data Sheet Preparation

First, the structure of a news table, the table is as follows:


4824974-cc14132c8fc97e06.jpg
image

Table of contents data is:


4824974-905e40d977440e43.jpg
image

2. Related

2.1 pom configuration file

Due to the integration mybatis in spring boot, the need to modify the pom.xml (maven project), add mybatis with mysql settings:

In vscode, select the pom.xml file, right click and choose Edit starters

4824974-0e5638ed8bbc14e5.jpg
image

Enter the same time check mysql, mybatis option as:


4824974-83d6779348fcd70a.jpg
image

After the update, pom.xml in more than two dependent options:

<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 Configuration options application.properties

Fill database accounts, passwords, etc. in the connection string application.properties configuration file is:

#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 Creating entity class

Project file directory is shown below:


4824974-2ad384547cd07cbd.jpg
image

Creating newsentity class, used to map the java file with the sql table;

//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 Creating Dao layer define specific data manipulation

(1) using the annotation style

Dao NewsDao.java defined in the annotation layer and the write process to implement database operations:

@Mapper
public interface NewsDao{

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

If the entity is passed in a class, you need to query results annotated map:

 /**
    * 保存
    * @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) using the xml manner

First define respective operations dao layer while adding annotations mapper 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);  
}

In the same directory NewsDao.java, the new NewsDao.xml file, define its specific sql database operations:

<?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 Method and implement service layer interface defined (particularly service logic layer)

Here we are additions and deletions to the operation of the news this table, so its interface definitions:

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);

   
}

service concrete realization:

//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);
    }
    
}

Note: Because here we define a service, in the spring, this spring NewsService want to register, handed over spring unified management of its container (IOC Inversion of Control)

So public class implements NewsService defined NewsServiceImpl in, remember to add comment @Service

@Service
public class NewsServiceImpl implements NewsService{

Otherwise, spring will complain can not find its service.

2.6controller layer: registered route reception parameters and

Here we test the query method with simple preservation method is normal:

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");
    }
    

When accessing / news / info / 2 returns the id of rows in Table 2 news.

When accessing / news / save / titlename time, add a title to the record titlename.

test:

Single-line query record:


4824974-7de63304a93bb249.jpg
image

Storage


4824974-390646b35e5840f3.jpg
image

4824974-57d6c9eccdd335de.jpg
image

testing successfully;

Guess you like

Origin blog.csdn.net/weixin_33851604/article/details/91023204