idea设计spring boot 多模块开发二【整合mybatis】

多模块搭建为上一篇博客,此处我们采用上篇博博客搭好的项目answers进行整合

  1. 创建数据库
  2. 引入相关jar
  3. 创建实体类
  4. 创建mapper类
  5. 创建sqlmapper.xml
  6. service代码
  7. 控制层代码
  8. 配置application.properties
  9. 启动类扫描mapper
  10. 测试

1.创建数据库,新建表 根据心情随便加两条数据

SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
--  Table structure for `tb_user`
-- ----------------------------
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
  `tu_id` bigint(255) NOT NULL COMMENT '用户id',
  `tu_username` varchar(16) COLLATE utf8_bin NOT NULL COMMENT '用户名',
  `tu_password` varchar(16) COLLATE utf8_bin NOT NULL COMMENT '密码',
  `tu_createdata` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '注册时间',
  `tu_phone` int(15) NOT NULL COMMENT '手机号',
  `tu_age` int(3) NOT NULL COMMENT '年龄',
  `tu_sex` int(1) NOT NULL COMMENT '性别',
  `tu_avatar` varchar(255) COLLATE utf8_bin NOT NULL COMMENT '头像',
  `tu_info` varchar(255) COLLATE utf8_bin NOT NULL COMMENT '信息',
  `tu_pid` bigint(8) NOT NULL COMMENT '所属省',
  `tu_cid` bigint(8) NOT NULL COMMENT '所属市',
  `tu_oid` bigint(8) NOT NULL COMMENT '所属区',
  `tu_status` int(20) NOT NULL COMMENT '状态:0删除 1正常 2冻结',
  PRIMARY KEY (`tu_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

2.因为我们将在answers-service进行数据库访问操作所以我们要在其pom.xml引入相关jar

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.9</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.0</version>
		</dependency>

3.在answers-domain中新建实体类TbUser与数据库对应 

package com.zes.answers.domain;

import java.util.Date;

public class TbUser {
    private Long tuId;

    private String tuUsername;

    private String tuPassword;

    private Date tuCreatedata;

    private Integer tuPhone;

    private Integer tuAge;

    private Integer tuSex;

    private String tuAvatar;

    private String tuInfo;

    private Long tuPid;

    private Long tuCid;

    private Long tuOid;

    private Integer tuStatus;

    public Long getTuId() {
        return tuId;
    }

    public void setTuId(Long tuId) {
        this.tuId = tuId;
    }

    public String getTuUsername() {
        return tuUsername;
    }

    public void setTuUsername(String tuUsername) {
        this.tuUsername = tuUsername == null ? null : tuUsername.trim();
    }

    public String getTuPassword() {
        return tuPassword;
    }

    public void setTuPassword(String tuPassword) {
        this.tuPassword = tuPassword == null ? null : tuPassword.trim();
    }

    public Date getTuCreatedata() {
        return tuCreatedata;
    }

    public void setTuCreatedata(Date tuCreatedata) {
        this.tuCreatedata = tuCreatedata;
    }

    public Integer getTuPhone() {
        return tuPhone;
    }

    public void setTuPhone(Integer tuPhone) {
        this.tuPhone = tuPhone;
    }

    public Integer getTuAge() {
        return tuAge;
    }

    public void setTuAge(Integer tuAge) {
        this.tuAge = tuAge;
    }

    public Integer getTuSex() {
        return tuSex;
    }

    public void setTuSex(Integer tuSex) {
        this.tuSex = tuSex;
    }

    public String getTuAvatar() {
        return tuAvatar;
    }

    public void setTuAvatar(String tuAvatar) {
        this.tuAvatar = tuAvatar == null ? null : tuAvatar.trim();
    }

    public String getTuInfo() {
        return tuInfo;
    }

    public void setTuInfo(String tuInfo) {
        this.tuInfo = tuInfo == null ? null : tuInfo.trim();
    }

    public Long getTuPid() {
        return tuPid;
    }

    public void setTuPid(Long tuPid) {
        this.tuPid = tuPid;
    }

    public Long getTuCid() {
        return tuCid;
    }

    public void setTuCid(Long tuCid) {
        this.tuCid = tuCid;
    }

    public Long getTuOid() {
        return tuOid;
    }

    public void setTuOid(Long tuOid) {
        this.tuOid = tuOid;
    }

    public Integer getTuStatus() {
        return tuStatus;
    }

    public void setTuStatus(Integer tuStatus) {
        this.tuStatus = tuStatus;
    }
}

4.在answers-service中新建包mapper ,其下创建UserMapper


UserMapper.java

package com.zes.answers.mapper;

import java.util.List;

import com.zes.answers.domain.TbUser;
public interface TbUserMapper {

    int deleteByPrimaryKey(Long tuId);

    int insert(TbUser record);

    int insertSelective(TbUser record);

    TbUser selectByPrimaryKey(Long tuId);

    int updateByPrimaryKeySelective(TbUser record);

    int updateByPrimaryKey(TbUser record);

    List<TbUser> findAllUser();

}

5.在ansers-service的resources下创建mapper用于存放sqlmapper.xml,此处我们存放TbUserMapper.xml


TbUserMapper.xml

扫描二维码关注公众号,回复: 168150 查看本文章
<?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.zes.answers.mapper.TbUserMapper">
  <resultMap id="baseMap" type="com.zes.answers.domain.TbUser">
    <id column="tu_id" jdbcType="BIGINT" property="tuId" />
    <result column="tu_username" jdbcType="VARCHAR" property="tuUsername" />
    <result column="tu_password" jdbcType="VARCHAR" property="tuPassword" />
    <result column="tu_createdata" jdbcType="TIMESTAMP" property="tuCreatedata" />
    <result column="tu_phone" jdbcType="INTEGER" property="tuPhone" />
    <result column="tu_age" jdbcType="INTEGER" property="tuAge" />
    <result column="tu_sex" jdbcType="INTEGER" property="tuSex" />
    <result column="tu_avatar" jdbcType="VARCHAR" property="tuAvatar" />
    <result column="tu_info" jdbcType="VARCHAR" property="tuInfo" />
    <result column="tu_pid" jdbcType="BIGINT" property="tuPid" />
    <result column="tu_cid" jdbcType="BIGINT" property="tuCid" />
    <result column="tu_oid" jdbcType="BIGINT" property="tuOid" />
    <result column="tu_status" jdbcType="INTEGER" property="tuStatus" />
  </resultMap>
  <sql id="Base_Column_List">
    tu_id, tu_username, tu_password, tu_createdata, tu_phone, tu_age, tu_sex, tu_avatar,
    tu_info, tu_pid, tu_cid, tu_oid, tu_status
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="baseMap">
    select
    <include refid="Base_Column_List" />
    from tb_user
    where tu_id = #{tuId,jdbcType=BIGINT}
  </select>
  <select id="findAllUser" resultMap="baseMap">
    select
    <include refid="Base_Column_List" />
    from tb_user
  </select>
</mapper>

6.Userservice以及UserServiceimpl代码

UserService.java

package com.zes.answers.service;

import java.util.List;

import com.zes.answers.domain.TbUser;

/**
 * TODO 类描述
 *
 * @author honghe
 */
public interface UserService {
    TbUser findUserById(Long id);
    List<TbUser> findAllUser();
}

UserServiceImpl.java

package com.zes.answers.service.Impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.zes.answers.domain.TbUser;
import com.zes.answers.mapper.TbUserMapper;
import com.zes.answers.service.UserService;

/**
 * TODO 类描述
 *
 * @author honghe
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    TbUserMapper userMapper;

    @Override
    public TbUser findUserById(Long id) {
        TbUser user = new TbUser();
        try {
            user  = userMapper.selectByPrimaryKey(id);
        }catch (Exception e){
            e.printStackTrace();
        }
        return user;
    }

    @Override
    public List<TbUser> findAllUser() {
        List<TbUser> userList = userMapper.findAllUser();
        System.out.println("数组长度为:"+userList.size());
        return userList;
    }

}

7.控制层UserController

package com.zes.answers.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zes.answers.service.UserService;

/**
 * TODO 类描述
 *
 * @author honghe
 */
@RequestMapping("/users")
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/getUserById")
    @ResponseBody
    public Map<String,Object> getUserById(String id){
        Map<String,Object> resutl = new HashMap<>();
        resutl.put("code","100");
        resutl.put("user",userService.findUserById(Long.valueOf(id)));
        return resutl;
    }

    @RequestMapping("/getAllUser")
    @ResponseBody
    public Map<String,Object> getAllUser(){
        Map<String,Object> resutl = new HashMap<>();
        resutl.put("code","100");
        resutl.put("user",userService.findAllUser());
        return resutl;
    }
}

8.添加配置answers-web的application.properties

spring.datasource.username=root
spring.datasource.password=mysqlsa123522
spring.datasource.url=jdbc:mysql://168.235.85.162:3306/cicada
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.minIdle=3
spring.datasource.maxWait=600000
spring.datasource.removeAbandoned=true
spring.datasource.removeAbandonedTimeout=180
spring.datasource.timeBetweenEvictionRunsMillis=600000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=50
spring.datasource.filters=stat

mybatis.mapper-locations=classpath*:mapper/*Mapper.xml
#mybatis.type-aliases-package=com.zes.answer.mapper

9.启动类扫描mapper

package com.zes.answers;

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

@SpringBootApplication
@MapperScan(value = "com.zes.answers.mapper")
public class AnswersWebApplication {

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

10.postman中进行接口的测试


11.项目git地址 https://gitee.com/zhaoershuang/answers.git

猜你喜欢

转载自blog.csdn.net/qq_37642205/article/details/80227196