SpringBoot+Mybatis+Maven+MySQL逆向工程实现增删改查

                  SpringBoot+Mybatis+MySQL+MAVEN逆向工程实现增删改查

    这两天简单学习了下SpringBoot,发现这玩意配置起来是真的方便,相比于SpringMVC+Spring的配置简直是天堂!!!

  当然学习SpringBoot必须要先学会SpringMVC和Spring。

    接下来是一个基于SpringBoot+Mybatis+MySQL+MAVEN的在IDEA环境下的简单的增删改查

    记录一下自己的学习过程也希望能帮助到需要的人

    第一次写博客有啥不对的地方请多多指教,多谢啦

 

 

    

    首先呢是环境的搭建:

SpringBoot+Mybatis+Maven+MySQL逆向工程实现增删改查_第1张图片

选中SpringInitializr

SpringBoot+Mybatis+Maven+MySQL逆向工程实现增删改查_第2张图片

 

选择JDK版本以及项目名称等

 

 

 

SpringBoot+Mybatis+Maven+MySQL逆向工程实现增删改查_第3张图片

选择Web+JPA+MySQL+Mybatis

 

最后的项目结构是

SpringBoot+Mybatis+Maven+MySQL逆向工程实现增删改查_第4张图片

SpringBoot+Mybatis+Maven+MySQL逆向工程实现增删改查_第5张图片

 

首先在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.0modelVersion>

    <groupId>com.examplegroupId>
    <artifactId>demoartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <packaging>jarpackaging>

    <name>demoname>
    <description>Demo project for Spring Bootdescription>

    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.0.4.RELEASEversion>
        <relativePath/> 
    parent>

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
        <java.version>10java.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-jpaartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>1.3.2version>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>

            <plugin>
                <groupId>org.mybatis.generatorgroupId>
                <artifactId>mybatis-generator-maven-pluginartifactId>
                <version>1.3.5version>
<configuration> <configurationFile>src\main\resources\generatorConfig.xmlconfigurationFile> <verbose>trueverbose> <overwrite>trueoverwrite> configuration> <dependencies> <dependency> <groupId>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> <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>
    
    
    <properties resource="generator.properties"/>
    
    <classPathEntry location="C:\Util\MySQL\mysql\mysql-connector-java-5.1.6-bin.jar" />

    
    
    <context id="MysqlTables" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        
        <property name="autoDelimitKeywords" value="true" />
        
        <property name="javaFileEncoding" value="utf-8" />
        
        <property name="beginningDelimiter" value="`" />
        <property name="endingDelimiter" value="`" />

        
        <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
        
        <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>

        
        <jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.user}" password="${jdbc.password}" />
        
        <javaTypeResolver>
            
            <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>
        
        <sqlMapGenerator targetPackage="mapper" targetProject="${resources}" >
            <property name="enableSubPackages" value="false" />
        sqlMapGenerator>
        
        <javaClientGenerator targetPackage="com.example.demo.dao" targetProject="${project}" type="XMLMAPPER" >
            <property name="enableSubPackages" value="false" />
        javaClientGenerator>
        
        <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

SpringBoot+Mybatis+Maven+MySQL逆向工程实现增删改查_第6张图片

运行!

UserMapper , UserMapper.xml , User实体类就会自动帮我们生成

如图SpringBoot+Mybatis+Maven+MySQL逆向工程实现增删改查_第7张图片

 

然后接着配置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

SpringBoot+Mybatis+Maven+MySQL逆向工程实现增删改查_第8张图片

启动!

然后打开localhost:8080



大功告成!打完收工! 告辞告辞。。。
                        
                          

 

 

转载于:https://www.cnblogs.com/Leslie-/p/9469045.html

你可能感兴趣的:(SpringBoot+Mybatis+Maven+MySQL逆向工程实现增删改查)