SpringBoot+Mybatis+MySQL+MAVEN逆向工程实现增删改查
这两天简单学习了下SpringBoot,发现这玩意配置起来是真的方便,相比于SpringMVC+Spring的配置简直是天堂!!!
当然学习SpringBoot必须要先学会SpringMVC和Spring。
接下来是一个基于SpringBoot+Mybatis+MySQL+MAVEN的在IDEA环境下的简单的增删改查
记录一下自己的学习过程也希望能帮助到需要的人
第一次写博客有啥不对的地方请多多指教,多谢啦
首先呢是环境的搭建:
选中SpringInitializr
选择JDK版本以及项目名称等
选择Web+JPA+MySQL+Mybatis
最后的项目结构是
首先在MAVEN中导入依赖,我自己用的是Mybatis的逆向工程创建UserMapper和User实体类,所以有generator两个配置文件
完整的POM配置如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>demo</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>10</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin> <plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<!--
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<phase>deploy</phase>
<goals>
<goal>generate</goal>
</goals>
<execution>
</executions>
-->
<configuration>
<configurationFile>src\main\resources\generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build> </project>
导入之后再右下角确定MAVEN下载依赖 然后呢咱们继续其他的配置
generator.property:
generator.properties #Mybatis Generator configuration
#dao类和实体类的位置
project=src/main/java
#mapper文件的位置
resources=src/main/resources
#根据数据库中的表生成对应的pojo类、dao、mapper
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/user
jdbc.user=root
jdbc.password=123456
配置数据库的连接 ,将数据库连接从generatorConfig里面抽取出来 ,这样做的好处不言而喻啦
接下来是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>
<!--执行generator插件生成文件的命令: call mvn mybatis-generator:generate -e -->
<!-- 引入配置文件 -->
<properties resource="generator.properties"/>
<!--classPathEntry:数据库的JDBC驱动,换成你自己的驱动位置 可选 -->
<classPathEntry location="C:\Util\MySQL\mysql\mysql-connector-java-5.1.6-bin.jar" /> <!-- 一个数据库一个context -->
<!--defaultModelType="flat" 大数据字段,不分表 -->
<context id="MysqlTables" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<!-- 自动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表;
一般保留默认值,遇到数据库关键字(Java关键字),使用columnOverride覆盖 -->
<property name="autoDelimitKeywords" value="true" />
<!-- 生成的Java文件的编码 -->
<property name="javaFileEncoding" value="utf-8" />
<!-- beginningDelimiter和endingDelimiter:指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号; -->
<property name="beginningDelimiter" value="`" />
<property name="endingDelimiter" value="`" /> <!-- 格式化java代码 -->
<property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
<!-- 格式化XML代码 -->
<property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
<plugin type="org.mybatis.generator.plugins.SerializablePlugin" /> <plugin type="org.mybatis.generator.plugins.ToStringPlugin" /> <!-- 注释 -->
<commentGenerator >
<property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->
<property name="suppressDate" value="true" /> <!-- 是否生成注释代时间戳-->
</commentGenerator> <!-- jdbc连接 -->
<jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.user}" password="${jdbc.password}" />
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver> <!-- 生成实体类地址 -->
<javaModelGenerator targetPackage="com.example.demo.entity" targetProject="${project}" >
<property name="enableSubPackages" value="false"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成mapxml文件 -->
<sqlMapGenerator targetPackage="mapper" targetProject="${resources}" >
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 生成mapxml对应client,也就是接口dao -->
<javaClientGenerator targetPackage="com.example.demo.dao" targetProject="${project}" type="XMLMAPPER" >
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- table可以有多个,每个数据库中的表都可以写一个table,tableName表示要匹配的数据库表,也可以在tableName属性中通过使用%通配符来匹配所有数据库表,只有匹配的表才会自动生成文件 -->
<table tableName="user" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="true">
<property name="useActualColumnNames" value="false" />
<!-- 数据库表主键 -->
<generatedKey column="id" sqlStatement="Mysql" identity="true" />
</table>
</context>
</generatorConfiguration>
然后找到右边的Maven Project
运行!
UserMapper , UserMapper.xml , User实体类就会自动帮我们生成
如图
然后接着配置application.property
jdbc.type=mysql
spring.datasource.url=jdbc:mysql://localhost:3306/user
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
接下来按照J2EE的开发方式 创建dao层 , service层 ,control层
结构如上图所示
再接下来是代码
UserMapper:
package com.example.demo.dao; import com.example.demo.entity.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository; import java.util.List; @Repository
@Mapper //不加注解可能出现扫描不到的情况
public interface UserMapper { @Delete("DELETE FROM user WHERE id = #{id}")
int deleteByPrimaryKey(Integer id); @Insert("INSERT INTO user (id,username,password,message) values ( #{id},#{username},#{password},#{message})")
int insert(User record); @Select("SELECT * FROM user WHERE id = #{id}")
User selectByPrimaryKey(Integer id); @Select("SELECT * FROM user ")
List<User> selectAll(); @Update("UPDATE user SET id = #{id}, username = #{username}, password = #{password}," +
"message = #{message} where id = #{id}")
int updateByPrimaryKey(User record);
}
我用的是基于注解的方式的SQL语言,这种适合于查询语句比较简单一点的,复杂的查询语句不推荐使用
UserService
package com.example.demo.service; import com.example.demo.entity.User; import java.util.List; /**
* author:lrh
* Date:2018/8/13
* Time:14:24
*/
public interface UserService {
public void insert(User user); public void delete(int id); public void update(User user); public User select(int id); public List<User> selectAll();
}
UserServiceImpl
package com.example.demo.service.impl; import com.example.demo.dao.UserMapper;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List; /**
* author:lrh
* Date:2018/8/13
* Time:14:50
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper; @Override
public void insert(User user) {
userMapper.insert(user);
} @Override
public void delete(int id) {
userMapper.deleteByPrimaryKey(id);
} @Override
public void update(User user) {
userMapper.updateByPrimaryKey(user);
} @Override
public User select(int id) {
return userMapper.selectByPrimaryKey(id);
} @Override
public List<User> selectAll() {
return userMapper.selectAll();
}
}
Service层没啥好说的 就是调用DAO层的方法
最后是Control层
UserControl:
package com.example.demo.control; import com.example.demo.entity.User;
import com.example.demo.service.UserService;
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; import java.util.List; /**
* author:lrh
* Date:2018/8/13
* Time:14:24
*/
@RestController
public class UserControl {
@Autowired
private UserService userService; @RequestMapping("/insert")
public void insert(User user){
userService.insert(user);
}
@RequestMapping("/delete/{id}")
public void delete(@PathVariable("id") int id){
userService.delete(id);
}
@RequestMapping("/update")
public void update(User user){
userService.update(user);
}
@RequestMapping("/select/{id}")
public User select(@PathVariable("id") int id){
return userService.select(id);
}
@RequestMapping("/selectAll")
public List<User> selectAll(){
return userService.selectAll();
} }
@RequestMapping是SpringMVC里的注解,比如在这个类里面就是当访问的是/select的URL时
就使用该方法 {}代表是一个占位符 最后打开DemoApplication,这个文件相当于是整个项目的入口
SpringBoot内置了Tomcat所以不需要在做其他的工作
直接启动main
启动! 然后打开localhost:8080
大功告成!打完收工! 告辞告辞。。。