Mac下idea从零创建springboot项目以及整合mybatis和mybatis逆向生成工具-springboot(1)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/babybabyup/article/details/84335054

前言

近期从SSM框架转为springboot开发restful风格的接口。网络上的资源质量良莠不齐,看了很多博客,有很多项目名字、项目代码、项目id等等等的东西统统一模一样但是按着来却是运行不通,我就奇了怪了,你们都是统一思考的么?

2018-11-28 更新

  • 寻找逆向生成器配置文件中的classpath方法 跳转

正文

对于之前有过从事SSM框架或者SSH框架开发的猿来说,springboot会简单很多,不用那么繁杂的各种配置文件,一个helloword项目,可能只需要几行代码而已。
本文将使用jetbrains公司的idea创建springboot项目,并且配置mybatis以及mybatis逆向代码生成器

原料及工具

  • jetbrains idea
  • 本地mysql数据库
  1. url:jdbc:mysql://localhost:3306/hello
  2. user:root
  3. password:Hlm970%&
  4. 数据库有一张表user

创建springboot项目

idea创建springboot项目真的简单,添加依赖也是简单至极。

新建目录

新建一个空白目录来存放项目,在desktop创建hellospring目录。
新建目录

创建并运行

打开软件选择create a new project,以及spring initializr,如图
新建选择

next 后,填写相应信息,这个看个人爱好了,对项目运行没有多大区别,这里选择maven管理工具,当然也可以gradle
填写信息
next后就是选择依赖的界面了,也可以在创建后pom.xml中手动添加。
点击左侧web
选择web
点击左侧sql
选择sql

next 后选择项目地址
项目地址
finish后等待创建完成。
最终文件目录如下:
文件目录

ok,现在写个测试api:
编辑HellospringAplication.java

package com.nick.hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class HellospringApplication {

	public static void main(String[] args) {
		SpringApplication.run(HellospringApplication.class, args);
	}

    /**
     * 测试api
     * @return 测试返回字符串
     */
	@RequestMapping(value = "/")
    public String index() {
	    return "ok!";
    }
}

修改application.properties

server.port=8080

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/hello?useUnicode=true&characterEncoding=utf-8&nullCatalogMeansCurrent=true
spring.datasource.username=root
spring.datasource.password=Hlm970%&

或者也可以选择更加简介的yml文件进行配置,点击运行:
运行

访问8080端口
访问
一个简单的api已经可以用了。

配置mybatis 逆向代码生成器

添加插件

修改pom.xml文件,新增generator插件

			<plugin>
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.3.2</version>
<configuration>
					<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
					<overwrite>true</overwrite>
					<verbose>true</verbose>
						</configuration>
			</plugin>

新建刚刚指定的src/main/resources/generatorConfig.xml,为了便于修改,我是又建了一个generator.properties文件来存储属性

generator.properties

#基本信息
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/hello?useUnicode=true&characterEncoding=utf-8&nullCatalogMeansCurrent=true
username=root
password=Hlm970%&

#entity 包名和 java目录
modelPackage=com.nick.hello.entity
modelProject=src/main/java

#sqlmap包名 和resources目录
sqlPackage=sqlmap
sqlProject=src/main/resources

#mapper包名和 java目录
mapperPackage=com.nick.hello.dao
mapperProject=src/main/java


table=user

generatorConfig.xml 要把classPathEntry中的location换成自己的。寻找方法

<?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="/Users/hulimin/.m2/repository/mysql/mysql-connector-java/8.0.13/mysql-connector-java-8.0.13.jar" />
    <context id="context1">
        <!-- 注释 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true" /><!-- 是否取消注释 -->
            <property name="suppressDate" value="true" /> <!-- 是否生成注释代时间戳 -->
        </commentGenerator>

        <jdbcConnection driverClass="${driver}"
                        connectionURL="${url}"
                        userId="${username}"
                        password="${password}" />

        <!-- 类型转换 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <javaModelGenerator targetPackage="${modelPackage}"
                            targetProject="${modelProject}" />
        <sqlMapGenerator targetPackage="${sqlPackage}" targetProject="${sqlProject}" />
        <javaClientGenerator targetPackage="${mapperPackage}"
                             targetProject="${mapperProject}" type="XMLMAPPER" />

        <!-- 如果需要通配所有表 直接用sql的通配符    %即可 -->
        <table schema="" tableName="${table}" enableCountByExample="false"
               enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" selectByExampleQueryId="false"
               
        >
            <!--<columnOverride column="REMARKS" javaType="java.lang.String" jdbcType="VARCHAR"/>-->
        </table>

    </context>
</generatorConfiguration>
使用插件生成代码

打开左侧maven project 找到Plugins->mybatis-generator,双击mybatis-generator:generator即可。如果没有这个插件,刷新试试.

generator
成功后会生成UserMapper.java User.java UserMapper.xml文件。在UserMapper添加@Repository注解。有对这6个函数不理解的可以看看这个:
https://blog.csdn.net/babybabyup/article/details/79761618

使用mybatis

代码生成后,就可以使用数据库函数了。
generator.properties中添加mybatis配置

mybatis.mapper-locations=classpath:sqlmap/*.xml

com.nick.hello包中新建services包,实现数据库接口,新建controller包进行业务逻辑操作。
包

services包中,新建UserService.java,并添加@Service注解.只用insert函数测试一下

package com.nick.hello.services;

import com.nick.hello.dao.UserMapper;
import com.nick.hello.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService implements UserMapper {

    @Autowired
    private UserMapper userMapper;

    @Override
    public int deleteByPrimaryKey(String id) {
        return 0;
    }

    @Override
    public int insert(User record) {
        return userMapper.insert(record);
    }

    @Override
    public int insertSelective(User record) {
        return 0;
    }

    @Override
    public User selectByPrimaryKey(String id) {
        return null;
    }

    @Override
    public int updateByPrimaryKeySelective(User record) {
        return 0;
    }

    @Override
    public int updateByPrimaryKey(User record) {
        return 0;
    }
}

controller包内新建TestContrller.java

package com.nick.hello.controller;

import com.nick.hello.entity.User;
import com.nick.hello.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
public class TestController {
    
    @Autowired
    private UserService userService;


    /**
     * 测试用
     * @param name 传入参数name
     * @param password 传入参数password
     * @return 插入结果,失败or成功+id
     */
    @RequestMapping(value = "insert", method = RequestMethod.GET)
    public String insertUser(@RequestParam("name") String name, @RequestParam("password") String password) {

        User user = new User();
        String id = UUID.randomUUID().toString().toLowerCase();
        user.setId(id);
        user.setName(name);
        user.setPassword(password);
        try {
            userService.insert(user);
            return "插入成功,其id为" + id;
        } catch (Exception e) {
            return "插入失败!";
        }
        
    } 
        
}

最后在HellospringApplication添加mapper扫描注解@MapperScan("com.nick.hello.dao")
运行后测试一下
浏览器
数据库中查看一下,数据库

OK了。哈哈哈哈哈啊哈

猜你喜欢

转载自blog.csdn.net/babybabyup/article/details/84335054