Spring Boot 快速入门之持久篇(三)

本贴最后更新于 2054 天前,其中的信息可能已经东海扬尘

一、前言

上一篇文章介绍了 Spring Boot 的一些 web 相关的内容,咱们接下这边文章就来讲一下开发离不开的数据。本篇以 MySql+MyBatis 为主。

二、整合 mysql 和 mybatis

2.1 配置 mysql 和 mybatis 版本

<properties> <java.version>1.8</java.version> <mysql.version>5.1.44</mysql.version> <mybatis.version>3.4.5</mybatis.version> <mybatis.springboot.version>1.3.1</mybatis.springboot.version> </properties>

2.2 添加依赖

<dependencies> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis.springboot.version}</version> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> </dependencies>

2.3 配置数据连接

在 application-dev.properties 中添加以下配置,可以在不同配置文件配置对应的数据源,需要时切换 application.properties 中的 spring.profiles.active=dev 即可。

#JDBC spring.datasource.driverClassName = com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://127.0.0.1:3306/springboot?allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai spring.datasource.username = root spring.datasource.password = Admin12345*

三、配置 Generator

3.1 添加 Generator 插件依赖

在 pom.xml 中添加以下配置:

<plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.3</version> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> <dependencies> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java 配置这个依赖主要是为了等下在配置MG的时候可以不用配置classPathEntry这样的一个属性,避免 代码的耦合度太高 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> </dependencies> </plugin>

3.2 新增 generator 配置文件

在 resource 文件夹下创建 generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <context id="ssm" targetRuntime="MyBatis3"> <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin" /> <plugin type="org.mybatis.generator.plugins.SerializablePlugin" /> <plugin type="org.mybatis.generator.plugins.CaseInsensitiveLikePlugin" /> <!-- <plugin type="org.mybatis.generator.plugins.ToStringPlugin"></plugin> --> <commentGenerator> <property name="suppressDate" value="true" /> <property name="suppressAllComments" value="true" /> </commentGenerator> <!-- 数据库连接 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/springboot" userId="root" password="Admin12345*"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- entity --> <javaModelGenerator targetPackage="com.y.springboot.model" targetProject="src/main/java"> <property name="constructorBased" value="true" /> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!--xml--> <sqlMapGenerator targetPackage="mybatis" targetProject="src/main/resources"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!--mapper.java--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.y.springboot.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 需要生成的表 tableName(表名) domainObjectName(生成的java类名称)--> <table schema="mybatis" tableName="user" domainObjectName="User"> <property name="constructorBased" value="true" /> <property name="useActualColumnNames" value="false" /> <property name="ignoreQualifiersAtRuntime" value="true" /> </table> </context> </generatorConfiguration>

四、测试

4.1 创建数据库表 user

CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_name` varchar(255) DEFAULT NULL, `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

4.2 生成 entity、mapper 和 xml

选择 IDEA 右侧 Maven--> Plugins --> mybatis-generator -->mybatis-generator:generator
会将数据库表按照 generatorConfig 配置的路径名称生成对应的 java 实体类和 xml 方法

1.gif

4.3 配置 spring 自动扫描和自动注入

在 application.properties 中添加:

#实体映射路径 #路径填写generatorConfig.xml中配置的路径 mybatis.mapper-locations = classpath:mybatis/*.xml mybatis.type-aliases-package = com.tes.sys.com.healthsafe.model

修改 SpringbootApplication

package com.y.springboot.springboot; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication(scanBasePackages = "com.y.springboot") @MapperScan("com.y.springboot.mapper") public class SpringbootApplication { public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); } }

4.4 测试类

TestService.java

package com.y.springboot.service; import com.y.springboot.model.User; public interface TestService { int addUser(User user); }

TestServiceImpl.java

package com.y.springboot.service; import com.y.springboot.mapper.UserMapper; import com.y.springboot.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class TestServiceImpl implements TestService { @Autowired private UserMapper userMapper; @Override public int addUser(User user) { return userMapper.insertSelective(user); } }

TestController.java

package com.y.springboot.springboot.controller; import com.y.springboot.model.User; import com.y.springboot.service.TestServiceImpl; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("test") public class TestController { @Autowired private TestServiceImpl testService; @ApiOperation(value = "新增用户",notes = "新增用户测试") @RequestMapping(value = "add",method = RequestMethod.POST) @ResponseBody public String add(){ User user = new User(); user.setUserName("测试"); user.setAge(20); int row = testService.addUser(user); if(row>0){ return "新增成功"; }else{ return "新增失败"; } } }

测试效果图:
2.gif

4.5 拓展 Example 的用法

本次使用 generator 生成的 java 实体会伴随一个对应的 Example 文件,可以用作去重/排序/分页/条件查询等操作

public void exampleTest(){ UserExample userExample = new UserExample(); //userName等于‘测试’且年龄等于20 userExample.createCriteria().andUserNameEqualTo("测试").andAgeEqualTo(20); //按照年龄降序排序 userExample.setOrderByClause("age desc"); List<User> userList = userMapper.selectByExample(userExample); }

更多详细 Example 操作请自行 baidu~

  • Spring

    Spring 是一个开源框架,是于 2003 年兴起的一个轻量级的 Java 开发框架,由 Rod Johnson 在其著作《Expert One-On-One J2EE Development and Design》中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件,同时为 JavaEE 应用程序开发提供集成的框架。

    948 引用 • 1460 回帖 • 2 关注
  • Java

    Java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的。Java 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3198 引用 • 8215 回帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...