版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014252106/article/details/88984524
mybatis是我们平常开发中使用频率最高的一款ORM框架,本节主要是基于
mybatis
官方提供的Starter进行整合。
准备工作
环境
- mysql 5.5+
首先,我们需要在数据库中新增一张t_notice表
init.sql
CREATE TABLE `t_notice` (
`id` varchar(36) NOT NULL COMMENT '逻辑主键',
`context` varchar(200) DEFAULT NULL COMMENT '公告内容',
`sort` int(11) DEFAULT NULL COMMENT '排序',
`is_use` int(11) DEFAULT NULL COMMENT '0--可用 1--不可用',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
其次,我们需要整合必要的jar包
//数据库依赖
compile 'org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.2'
compile 'mysql:mysql-connector-java:5.1.40'
//单元测试
testCompile 'org.springframework.boot:spring-boot-starter-test'
使用
-
修改application.yml
application.yml
mybatis: mapper-locations: classpath*:mapper/*Mapper.xml #需要扫瞄的xml文件 spring: datasource: url: jdbc:mysql://{数据库地址}/{数据库名}?useUnicode=true&characterEncoding=utf-8 username: {数据库登录名} password: {数据库密码} #没有的话,可删去 driver-class-name: com.mysql.jdbc.Driver
-
在src/main/java下添加NoticeService.java,NoticeMapper.java,Notice.java
NoticeService.java
package com.boot.demo.service; import com.boot.demo.entity.Notice; import com.boot.demo.mapper.NoticeMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.UUID; @Service public class NoticeService { @Autowired private NoticeMapper noticeMapper; public List<Notice> getList(){ return noticeMapper.getList(); } @Transactional public void save(Notice notice){ String noticeId = notice.getId(); if(null != noticeId && "" != noticeId){ noticeMapper.updateNotice(notice); } else { notice.setId(UUID.randomUUID().toString()); noticeMapper.insertNotice(notice); } } @Transactional public void remove(String id){ noticeMapper.removeNotice(id); } }
NoticeMapper.java
package com.boot.demo.mapper; import com.boot.demo.entity.Notice; import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper public interface NoticeMapper { //获取列表 List<Notice> getList(); //新增 void insertNotice(Notice notice); //更新 void updateNotice(Notice notice); //删除 void removeNotice(String id); }
Notice.java
package com.boot.demo.entity; import java.util.Date; public class Notice { private String id; private String context; private Integer sort; private Byte isUse; private Date createTime; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getContext() { return context; } public void setContext(String context) { this.context = context; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public Byte getIsUse() { return isUse; } public void setIsUse(Byte isUse) { this.isUse = isUse; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
-
在src/main/resources下新增mapper文件夹,并添加NoticeMapper.xml
NoticeMapper.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.boot.demo.mapper.NoticeMapper"> <resultMap id="notice" type="com.boot.demo.entity.Notice"> <id column="id" property="id" javaType="string"/> <result column="context" property="context" javaType="string"/> <result column="sort" property="sort" javaType="int"/> <result column="is_use" property="isUse" javaType="byte" /> <result column="create_time" property="createTime" javaType="java.util.Date"/> </resultMap> <select id="getList" resultMap="notice"> select id, context, sort, is_use, create_time FROM t_notice </select> <insert id="insertNotice" parameterType="com.boot.demo.entity.Notice"> insert into t_notice <trim prefix="(" suffix=")" suffixOverrides=","> <if test="null != id and '' != id"> id, </if> <if test="null != context and '' != context"> context, </if> <if test="null != sort"> sort, </if> <if test="null != isUse"> is_use, </if> create_time </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="null != id and '' != id"> #{id}, </if> <if test="null != context and '' != context"> #{context}, </if> <if test="null != sort"> #{sort}, </if> <if test="null != isUse"> #{isUse}, </if> now() </trim> </insert> <update id="updateNotice" parameterType="com.boot.demo.entity.Notice"> update t_notice <set> <if test="null != context and '' != context"> context = #{context}, </if> <if test="null != sort"> sort = #{sort}, </if> <if test="null != isUse"> is_use =#{isUse}, </if> </set> where id = #{id} </update> <delete id="removeNotice" parameterType="string"> delete from t_notice where id = #{id} </delete> </mapper>
-
在src/test/java下新增测试类NoticeTest.java
NoticeTest.java
package com.boot.demo.test; import com.boot.demo.entity.Notice; import com.boot.demo.service.NoticeService; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest(properties = "spring.main.web-application-type=reactive") public class NoticeTest { private static final Logger logger = LoggerFactory.getLogger(NoticeTest.class); @Autowired private NoticeService noticeService; @Test public void getNoticeListTest(){ ObjectMapper objectMapper = new ObjectMapper(); List<Notice> notices = noticeService.getList(); for(Notice notice : notices){ try { logger.info(objectMapper.writeValueAsString(notice)); } catch (JsonProcessingException e) { logger.error(e.getMessage(),e); } } } @Test public void addNotice(){ //新增 Notice notice = new Notice(); notice.setContext("呵呵哒"); notice.setSort(0); noticeService.save(notice); } @Test public void updateNotice(){ Notice notice = new Notice(); notice.setId("noticeId"); //noticeId替换为需要操作的记录id notice.setIsUse((byte)1); noticeService.save(notice); } @Test public void removeNotice(){ noticeService.remove("noticeId"); //noticeId替换为需要操作的记录id } }
好了,到这里,Spring Boot整合mybatis就结束了。各位读者大大们,可以通过运行以上的测试类,自行测试是否整合完成。
说一句
以上的内容是基于已经使用过mybatis的读者们设计的,如果对于mybatis的语法还不是很清楚,本文末尾会附上mybatis的文档地址,读者朋友可以自行查阅。