springboot+mybatis+maven+mysql项目从0到1实现连接数据库进行用户注册(idea2018)

1.新建maven项目

Group:项目包名称

Artifact:项目名称

需要加入的依赖:

使用 YAML 替代 properties 配置文件, 将 application.properties 改名为application.yml
个人不太喜欢properties类型的配置文件, 一是重复单词太多, 二是中文注释的编码转来转去, 经常会变乱码, spring boot支持YAML格式的配置

 

2.配置数据源

application.yml添加以下内容

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf8&autoReconnect=true
    username: root
    password: 123456

启动项目

 

3.新建数据库并建立表

新建表

CREATE TABLE `user` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `password` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `user_name_uindex` (`name`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4;

 

4.在pom.xml节点dependencies添加jar依赖

这个地方需要注意一下,com.alibaba这个是需要引用jar包的,如果没有就下载一个引入进来,引入包参考一下操作:

https://blog.csdn.net/zwj1030711290/article/details/56678353/

我下载的是这个fastjson-1.2.51.jar,所以在配置是需要保持版本一致。

         <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.51</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

 

5.创建包及类,接口文件目录

一般稍微上规模的项目都会先做一个详细设计,如果项目小也必须要先做一个基本的项目方案,确定项目的分层结构层级,这样在代码开发的时候尽量做到代码复用,抽象共同的或者是基础功能出来简化代码和维护的工作量。

UserApi

package com.hpm.blog.api;


import com.alibaba.fastjson.JSONObject;
import com.hpm.blog.model.User;
import com.hpm.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/user")
public class UserApi {
    private UserService userService;

    @Autowired
    public UserApi(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("")
    public Object add(@RequestBody User user) {
        if (userService.findByName(user.getName()) != null) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("error","用户名重复");
            return jsonObject;
        }
        return userService.add(user);
    }

    @GetMapping("{id}")
    public Object findById(@PathVariable int id) {
        return userService.findById(id);
    }
}

UserMapper

package com.hpm.blog.mapper;

import com.hpm.blog.model.User;


public interface UserMapper {
    int add(User user);

    User findOne(User user);
}

User

package com.hpm.blog.model;

import com.hpm.blog.mapper.*;

public class User {
    private Integer id;
    private String name;
    private String password;

    // 下面是 getter 和 setter 方法。。。
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

UserService

package com.hpm.blog.service;


import com.hpm.blog.mapper.UserMapper;
import com.hpm.blog.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Service
public class UserService {
    private UserMapper userMapper;

    @Autowired
    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public User add(User user) {
        String passwordHash =  passwordToHash(user.getPassword());
        user.setPassword(passwordHash);
        userMapper.add(user);
        return findById(user.getId());
    }

    private String passwordToHash(String password) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            digest.update(password.getBytes());
            byte[] src = digest.digest();
            StringBuilder stringBuilder = new StringBuilder();
            for (byte aSrc : src) {
                String s = Integer.toHexString(aSrc & 0xFF);
                if (s.length() < 2) {
                    stringBuilder.append('0');
                }
                stringBuilder.append(s);
            }
            return stringBuilder.toString();
        } catch (NoSuchAlgorithmException ignore) {
        }
        return null;
    }

    public User findById(int id) {
        User user = new User();
        user.setId(id);
        return userMapper.findOne(user);
    }

    public User findByName(String name) {
        User param = new User();
        param.setName(name);
        return userMapper.findOne(param);
    }

    public boolean comparePassword(User user, User userInDataBase) {
        return passwordToHash(user.getPassword())
                .equals(userInDataBase.getPassword());
    }
}

SpringBootBlogApplication添加@MapperScan注解

package com.hpm.blog;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.hpm.blog.mapper")
public class SpringBootBlogApplication {

    public static void main(String[] args) {

        SpringApplication.run(SpringBootBlogApplication.class, args);
    }
}

 

6.编写UserMapper.xml文件

UserMapper.xml文件夹层级及文件夹路径名称必须与类名及类所在的路径完全一致

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.hpm.blog.mapper.UserMapper">
    <insert id="add" useGeneratedKeys="true" keyProperty="id">
        insert into user(name, password) values (#{name},#{password})
    </insert>

    <select id="findOne" resultType="User">
        select * from user
        <where>
            <!-- 重复说一下,id 不能是 int,int 默认是 0,不可能是 null, 而 Integer 可以是 null-->
            <if test="id!=null">
                id=#{id}
            </if>
            <if test="name!=null">
                name=#{name}
            </if>
        </where>
    </select>
</mapper>

 

7.编写mybatis.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.hpm.blog.mapper.UserMapper">
    <insert id="add" useGeneratedKeys="true" keyProperty="id">
        insert into user(name, password) values (#{name},#{password})
    </insert>

    <select id="findOne" resultType="User">
        select * from user
        <where>
            <!-- 重复说一下,id 不能是 int,int 默认是 0,不可能是 null, 而 Integer 可以是 null-->
            <if test="id!=null">
                id=#{id}
            </if>
            <if test="name!=null">
                name=#{name}
            </if>
        </where>
    </select>
</mapper>

在application.yml中添加配置

mybatis:
  type-aliases-package: com.hpm.blog.model
  config-location: classpath:mybatis.xml

使用springboot扫码mapper文件,在SpringBootBlogApplication中添加注解:

@MapperScan("com.hpm.blog.mapper")

 

9.启动项目服务,进行注册测试

再次调用注册接口

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值