Spring Boot搭建及简单使用

本文介绍了如何从官网获取并创建Spring Boot项目,详细步骤包括项目创建、Hello World实现和数据库配置。在数据库配置部分,讲解了极致简陋版的配置以及集成Mybatis-generator插件的自动化代码生成,帮助快速启动和运行项目。
摘要由CSDN通过智能技术生成

一、 项目创建

1. 官网获取 Spring Boot项目

2. 本地创建

修改项目路径(项目域名反过来,例 com.wpx1997.community)和名称

选择依赖

添加一些必要的插件,建议maven仓库查找

Maven仓库

 

二、让项目跑起来

1. Hello Word

(1)创建controller层,创建IndexController类,加上@Controller注解

(2)在templates目录下创建index.html文件

(3)在application.properties文件中配置端口

(4)因为未配置数据源,需要在Application类中声明

@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})

(5)启动项目,在浏览器中输入对应的地址,可以看到跳到了对应的页面

 

三、配置数据库(增加灵魂)

1. 极致简陋版

(1)创建数据库:

create database test

(2)创建数据库表:

create table tset_user
(
	id bigint auto_increment,
	name varchar(16),
	age int,
	constraint tset_user_pk
		primary key (id)
);

(3)配置数据源:

 

(4)根据之前建好的数据库表创建model层(用了lombok的@Data注解自动生成get和set方法以及构造器)

package com.example.demo.model;

import lombok.Data;

/**
 * created by 小case on 2020/6/5 9:34
 */
@Data
public class TestUser {
    private Long id;
    private String name;
    private Integer age;
}

(5)创建对应的mapper接口(尽量用 # 符号,不要用 $ 符号,如果数据库表有索引,就用 #{column,jdbcType=BIGINT})

package com.example.demo.mapper;

import com.example.demo.model.TestUser;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * created by 小case on 2020/6/5 9:49
 */
@Mapper
public interface TestUserMapper {

    @Insert("insert into test_user(name,age)values(#{name,jdbcType=VARCHAR},#{age,jdbcType=INT})")
    @Options(useGeneratedKeys=true,keyColumn="id")
    int insert(TestUser testUser);

    @Select("select * from test_user where id = #{id,jdbcType=BIGINT}")
    TestUser selectById(Long id);

    @Select("select * from test_user where name = #{name,jdbcType=VARCHAR}")
    List<TestUser> selectByName(String name);

}

(6)创建测试Controller

package com.example.demo.controller;

import com.example.demo.model.TestUser;
import com.example.demo.service.TestUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * created by 小case on 2020/6/4 18:54
 */
@Controller
public class IndexController {

    @Autowired
    private TestUserService testUserService;

    @GetMapping("/")
    public String index(){
        return "index";
    }

    @PostMapping("/insert")
    public String indexInsert(@RequestParam(value = "name") String name,
                              @RequestParam(value = "age") Integer age,
                              Model model){

        Long id = testUserService.insert(name,age);
        model.addAttribute("id",id);

        return "index";
    }

    @GetMapping("/user/{id}")
    public String userId(@PathVariable(name = "id") Long id,
                         Model model){

        TestUser testUser = testUserService.selectById(id);
        model.addAttribute("testUser",testUser);

        return "user";
    }

    @GetMapping("/list/{name}")
    public String list(@PathVariable(name = "name") String name,
                         Model model){

        List<TestUser> testUserList = testUserService.selectByName(name);
        model.addAttribute("testUserList",testUserList);

        return "user";
    }

}

(7)创建测试Service

package com.example.demo.service;

import com.example.demo.mapper.TestUserMapper;
import com.example.demo.model.TestUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * created by 小case on 2020/6/5 10:18
 */
@Service
public class TestUserService {

    @Autowired
    private TestUserMapper testUserMapper;

    public Long insert(String name, Integer age) {

        TestUser testUser = new TestUser();
        testUser.setName(name);
        testUser.setAge(age);
        testUserMapper.insert(testUser);
        Long id = testUser.getId();

        return id;
    }

    public List<TestUser> selectByName(String name){

        List<TestUser> testUserList = testUserMapper.selectByName(name);

        return testUserList;
    }

    public TestUser selectById(Long id){

        TestUser testUser = testUserMapper.selectById(id);

        return testUser;
    }

}

(8)启动项目

(9)输入数据并提交

(10)成功插入并返回id

(11)根据id查找数据

2. 集成Mybatis-generator插件

(1)添加依赖(里面的数据库依赖版本要和之前的一致)

(2)修改数据源

mybatis.mapper-locations=com.example.demo.mapper/*.xml

改为  mybatis.mapper-locations=classpath:mapper/*.xml

(3)在resources目录下添加配置文件 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="DB2Tables" targetRuntime="MyBatis3">

        <plugin type="org.mybatis.generator.plugins.RowBoundsPlugin"></plugin>

        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/test"
                        userId="root"
                        password="*****">
        </jdbcConnection>

        <javaTypeResolver >
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <javaModelGenerator targetPackage="com.example.demo.model" targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="mapper"  targetProject="src/main/resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.demo.mapper"  targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        
        <!--    配置生成数据库表对应的model类   -->
        <table tableName="test_user" domainObjectName="TestUser" ></table>

        <!--    如需返回主键   -->
        <table tableName="test_user" domainObjectName="TestUser" >
            <generatedKey column="id" sqlStatement="Mysql" identity="true" />
        </table>

    </context>
</generatorConfiguration>

配置好自己对应的数据库名,项目路径和表信息

(4)删除原来的model层和mapper层,在Terminal运行命令

mvn -Dmybatis.generator.overwrite=true mybatis-generator:generate

运行完后可以看到目录中多了三个文件夹

(5)我们把原来Service层的代码改一下

package com.example.demo.service;

import com.example.demo.mapper.TestUserMapper;
import com.example.demo.model.TestUser;
import com.example.demo.model.TestUserExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * created by 小case on 2020/6/5 10:18
 */
@Service
public class TestUserService {

    @Autowired
    private TestUserMapper testUserMapper;

    public Long insert(String name, Integer age) {

        TestUser testUser = new TestUser();
        testUser.setName(name);
        testUser.setAge(age);
        testUserMapper.insert(testUser);
        Long id = testUser.getId();

        return id;
    }

    public List<TestUser> selectByName(String name){

        TestUserExample testUserExample = new TestUserExample();
        testUserExample.createCriteria().andNameEqualTo(name);
        List<TestUser> testUserList = testUserMapper.selectByExample(testUserExample);

        return testUserList;
    }

    public TestUser selectById(Long id){

        TestUser testUser = testUserMapper.selectByPrimaryKey(id);

        return testUser;
    }

}

(6)运行项目

可以看到,项目已经可以正常运行了,还不需要手写数据库语句(必要时可以拓展)

四、Mybatis-generator学习

Mybatis-generator官网

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值