spring boot(二):Mybatis操作数据库

2019-06-01  本文已影响0人  寒夏凉秋

(1)mysql数据表准备

首先,准备一张news的表,表的结构为:


image

数据中的表的内容为:


image

2.相关配置

2.1配置pom文件

由于在spring boot 中整合mybatis,需要修改pom.xml(maven 项目),添加mybatis 跟mysql 的设置:

在vscode 中,选择pom.xml 文件,右键选择Edit starters

image

输入同时勾选mysql、mybatis选项,如图:


image

更新后,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 创建entity类

项目文件目录为图所示:


image

创建newsentity类,用来java文件与sql 表的映射;

//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创建Dao层定义具体数据操作

(1)利用注解的方式

在dao层中定义了NewsDao.java 然后将注解写在方法中来实现数据库操作:

@Mapper
public interface NewsDao{

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

如果是传入的是entity 类,则需要对查询结果进行注解映射:

 /**
    * 保存
    * @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添加mapper注解:

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定义service层接口方法与实现(具体业务层逻辑)

这里我们对news 这个表进行增删改操作,所以定义其接口:

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 的具体实现:

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

注意:因为在这里我们定义了一个service,在spring 中,这个NewsService要注册到spring,交由spring统一管理其容器(IOC控制反转)

所以在public class NewsServiceImpl implements NewsService定义中,记得加上@Service 注解

@Service
public class NewsServiceImpl implements NewsService{

不然spring会报错无法找到其服务.

2.6controller层:注册路由与接收参数

在这里我们简单测试一下查询方法跟保存方法是否正常:

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

当访问/news/info/2的时候,返回的是id为2的news表的行记录.

当访问/news/save/titlename的时候,新增一条title 为titlename的记录.

测试:

查询单行记录:


image

保存


image
image

测试成功;

上一篇下一篇

猜你喜欢

热点阅读