接口开发-集成数据库操作(mybatis)

关于数据存储,最常用的方式就是存到数据库,此篇以MySQL数据库为例,以mybatis框架完成数据库的操作。

一、添加对应依赖

        <!-- 数据库:MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
        </dependency>

        <!-- 数据库操作:mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis-spring-boot}</version>
        </dependency>

(等待依赖库下载完成以后,再继续)  

二、properties文件、数据库表

(1)properties文件

## 数据源配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/apidemo?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=your db password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

## Mybatis 配置
mybatis.typeAliasesPackage=com.univalsoft.api.springbootapimaster.entity
mybatis.mapperLocations=classpath:mapper/*.xml  

(记住,在properties文件中添加了相应的配置以后,mybatis会自动读取并完成初始化)

(2)数据库表

 

三、编写对应的service/serviceImpl/dao/mapper文件

(1)service(com.univalsoft.springbootapimaster.api.service.AccontService)

package com.univalsoft.springbootapimaster.api.service;

import java.util.HashMap;

/**
 * 账号业务逻辑接口类
 * <p>
 * Created by bysocket on 07/02/2017.
 */
public interface AccountService {

    /**
     * 根据用户名查询
     *
     * @param username 用户名
     * @param password 密码
     */
    HashMap<String, Object> findUser(String username, String password);

}

  

(2)serviceImpl(com.univalsoft.springbootapimaster.api.service.impl.AccountServiceImpl)

package com.univalsoft.springbootapimaster.api.service.impl;

import com.univalsoft.springbootapimaster.api.dao.AccountDao;
import com.univalsoft.springbootapimaster.api.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;


@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    @Override
    public HashMap<String, Object> findUser(String username, String password) {
        return accountDao.findUserByAccount(username, password);
    }
}

  

(3)dao(com.univalsoft.springbootapimaster.api.dao.AccountDao)

package com.univalsoft.springbootapimaster.api.dao;

import org.apache.ibatis.annotations.Param;

import java.util.HashMap;

/**
 * 账号 DAO 接口类
 */
public interface AccountDao {

    /**
     * 查询用户
     *
     * @param username 用户名
     * @param password 密码
     */
    HashMap<String, Object> findUserByAccount(@Param("username") String username,
                                              @Param("password") String password);
}

  

(4)mapper(src/main/resources/mapper/AccountMapper.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.univalsoft.springbootapimaster.api.dao.AccountDao">

	<!-- 通过用户名、密码查找用户 -->
	<select id="findUserByAccount" resultType="hashmap">
		select * from t_user
		where 1=1
		<if test="username != null and username != ''">
			and username = #{username}
		</if>
		<if test="password != null and password != ''">
			and password = #{password}
		</if>
		limit 1
	</select>

</mapper>

(注意:红色标注出来的,对应的dao文件,路径一定要正确)  

 

四、在SpringbootApiMasterApplication.java添加@MapperScan注解

 

五、修改Controller文件

    @RequestMapping(value = "/api/test/login", method = RequestMethod.POST)
    public APIResponse login(
            @RequestParam(value = "username") String username /* 账号 */,
            @RequestParam(value = "password") String password /* 密码 */
    ) {

        // 当前版本,username为手机号,
        if (username.length() < 11) {
            return this.fail("请输入正确的手机号");
        }

        try {
            // password往往会加密,这里不做加密处理
            HashMap user =  accountService.findUser(username, password);
            if (user != null) {
                return this.success(user);
            } else {
                return this.fail("账号、密码错误");
            }
        } catch (Exception e) {
            return this.fail("");
        }
    }  

还是那句话,看不懂的,自觉找个地方面壁去!!!

 

六、Postman测试一下

  

通过Mybatis连接MySQL数据库的部分,到此结束了。

 

最后补充一个“招式”,通过IDEA的DB功能,加快SQL语句的书写

(1)配置DataBase

这样配置好以后,当在Mapper.xml中写SQL的时候,IDEA会给出很多友好的提示,nice~~~

 

posted @ 2019-01-07 14:46  环球移动团队  阅读(610)  评论(0编辑  收藏  举报