本文已参与「新人创作礼」活动,一起开启掘金创作之路
一、基础环境准备工作
1、在Navicat中新建查询,创建数据库develop并在库中创建两张表t_article和t_comment,运行以下脚本即可
#创建数据库
CREATE DATABASE develop;
#选择使用数据库
USE develop;
#创建表t_article并插入相关数据
DROP TABLE IF EXISTS t_article; CREATE TABLE t_article ( id int(20) NOT NULL AUTO_INCREMENT COMMENT '文章id', title varchar(200) DEFAULT NULL COMMENT '文章标题', content longtext COMMENT '文章内容', PRIMARY KEY (id) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; INSERT INTO t_article VALUES ('1', 'Spring Boot基础入门', '从入门到精通...'); INSERT INTO t_article VALUES ('2', 'Spring Cloud基础入门', '从入门到精通...');
#创建表t_comment并插入相关数据
DROP TABLE IF EXISTS t_comment; CREATE TABLE t_comment ( id int(20) NOT NULL AUTO_INCREMENT COMMENT '评论id', content longtext COMMENT '评论内容', author varchar(200) DEFAULT NULL COMMENT '评论作者', a_id int(20) DEFAULT NULL COMMENT '关联的文章id', PRIMARY KEY (id) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; INSERT INTO t_comment VALUES ('1', '很全、很详细', '牛牛不怕困难', '1'); INSERT INTO t_comment VALUES ('2', '赞一个', 'Tom', '1'); INSERT INTO t_comment VALUES ('3', '很详细', 'Kitty', '1'); INSERT INTO t_comment VALUES ('4', '很好,非常详细', '张三', '1'); INSERT INTO t_comment VALUES ('5', '很不错', 'Lisa', '2');
2、在项目pom.xml中引入Mysql和Mybatis的相关依赖启动器
<!-- Mybatis启动器-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- Mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<!-- Druid数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
3、编写数据库表对应的实体类
import java.util.List;
public class Article {
private Integer id;
private String title;
private String Content;
private List<Comment> commentList;
//省略setter和getter方法
//省略toString方法
}
public class Comment {
private Integer id;
private String content;
private String author;
private Integer aId;
//省略setter和getter方法
//省略toString方法
}
4、编写application.properties配置文件,连接数据库和数据源信息
#配置Mysql数据库信息
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/develop?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
#配置第三方数据源Druid信息
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.initialSize=20
spring.datasource.minIdle=10
spring.datasource.maxActive=100
5、在src/main/java/com/chen/config包下创建DataSourceConfig自定义配置类对Druid数据源属性值进行注入
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource getDruid(){
return new DruidDataSource();
}
}
二、使用注解的方式整合Mybatis
1、在src/main/java/com/chen下新建一个mapper包,创建Mapper接口文件CommentMapper类
import com.chen.domain.Comment;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Component;
@Mapper// 表明该类为一个Mybatis接口文件,由SpringBoot自动扫描到Spring容器中
@Component
public interface CommentMapper {
@Select("select * from t_comment where id=#{id}")//查询注解
public Comment findByID(Integer id);
@Insert("insert into t_comment(content,author,a_id) values(#{content},#{author},#{aId})")// 插入注解
public int insertComment(Comment comment);
@Delete("delete from t_comment where id=#{id}")// 删除注解
public int deleteComment(Integer id);
@Update("update t_comment set content=#{content} where id=#{id}")// 更新注解
public int updateComment(Comment comment);
}
mapper类说明
由@Mapper表明该类是一个Mapper接口文件
也可以直接在启动类上注解@MapperScan("com.chen.mapper")统一配置识别Mapper接口文件所在的包路径(多个Mapper文件时避免逐个接口文件配置@Mapper注解这么麻烦)
在类的内部使用@Select、 @Insert、@Delete、 @Update注解配合SQL语句完成对数据库表的增删改查操作
2、创建一个测试类,测试接口的使用
import com.chen.domain.Comment;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MapperTest {
@Autowired
private CommentMapper commentMapper;
@Test
public void findComment(){
Comment comment = commentMapper.findByID(2);
System.out.println(comment);
}
}
3、运行测试类
从结果中可以看出,数据已经被查出来了,但是aId为null,看一下数据库表是有值的
ORM映射该值失败是因为没有开启驼峰命名规则,因此只需要在application.properties中开启驼峰命名规则即可
#开启驼峰命名
mybatis.configuration.map-underscore-to-camel-case=true
再次运行测试类
三、使用配置文件的方式整合Mybatis(实际开发常用方式)
1、在src/main/java/com/chen/mapper中创建Mapper接口文件
import com.chen.domain.Article;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
@Mapper
@Component
public interface ArticleMapper {
public Article selectArticle(Integer id);
public int updateArticle(Article article);
}
2、在resource目录下新建mapper包,创建xml映射配置文件
<?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.chen.mapper.ArticleMapper">
<!-- 1、查询文章详细(包括评论信息) -->
<select id="selectArticle" resultMap="articleWithComment">
SELECT a.*,c.id c_id,c.content c_content,c.author
FROM t_article a,t_comment c
WHERE a.id=c.a_id AND a.id = #{id}
</select>
<resultMap id="articleWithComment" type="Article">
<id property="id" column="id" />
<result property="title" column="title" />
<result property="content" column="content" />
<collection property="commentList" ofType="Comment">
<id property="id" column="c_id" />
<result property="content" column="c_content" />
<result property="author" column="author" />
</collection>
</resultMap>
<!-- 2、根据文章id更新文章信息 -->
<!--parameterType没有类的全路径名称,而使用别名,需要在全局配置文件中配置实体类的别名映射路径-->
<update id="updateArticle" parameterType="Article" >
UPDATE t_article
<set>
<if test="title !=null and title !=''">
title=#{title},
</if>
<if test="content !=null and content !=''">
content=#{content}
</if>
</set>
WHERE id=#{id}
</update>
</mapper>
xml映射文件说明,namespace属性值使用接口文件Mapper的全路径名称(注意不能漏了)
3、配置XML映射文件路径
#配置Mybatis的xml配置文件路径
mybatis.mapper-locations=classpath:mapper/*.xml
#配置xml映射文件中指定的实体类别名路径
mybatis.type-aliases-package=com.chen.domain
4、编写测试类
import com.chen.domain.Article;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MapperAndXMLTest {
@Autowired
private ArticleMapper articleMapper;
@Test
public void selectArticle(){
Article article = articleMapper.selectArticle(1);
System.out.println(article);
}
}
5、debug运行测试类,便于查看数据
可以看出selectArticle()执行成功,查询出了文章id为1的文章详情,并关联查询出了对应的评论信息。