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