SpringBoot脚手架 | 第1章:整合MySQL+Mybatis

本文介绍如何使用IDEA工具快速构建基于MyBatis框架的项目,并详细讲解了配置数据库连接、创建实体类、映射文件及DAO层等步骤。

一:通过idea工具构建基础框架

 1.  打开idea,左上角File→New→Project,看到如下图的页面

2.  点击Next,配置如下图
  3.  点击Next,配置如下图,这里我们选择数据库MySQL和持久层框架MyBatis
  4.  点击Next,选择工作目录,点击Finish,开始构建

 

  5.  创建完成后,项目目录结构如下

DemoApplicttion.java为项目的启动类

application.properties为项目配置文件

pom.xml主要描述了项目的maven坐标,依赖关系,开发者需要遵循的规则,缺陷管理系统,组织和licenses,以及其他所有的项目相关因素,是项目级别的配置文件(说人话:项目所需jar包的管理)

二:配置数据库信息

在application.properties文件中添加如下数据库配置

spring.datasource.url=jdbc:mysql://localhost:3306/demo?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&autoReconnect=true&failOverReadOnly=false
spring.datasource.username=数据库用户名
spring.datasource.password=数据库密码
spring.datasource.driverClassName=com.mysql.jdbc.Driver复制代码

三:创建数据库UserInfo表

CREATE TABLE `user_info` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; 复制代码

四:创建项目基本目录结构

Model

package com.example.demo.model;

import javax.persistence.Column;
import javax.persistence.Id;

/**
 * @author 张瑶
 * @Description:
 * @time 2018/4/18 11:55
 */
public class UserInfo {

    /**
     * 主键
     */
    @Id
    private String id;

    /**
     * 用户名
     */
    @Column(name = "user_name")
    private String userName;

    private String password;

    public String getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

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

}
复制代码

Mapper

<?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.example.demo.dao.UserInfoMapper">
    <resultMap id="BaseResultMap" type="com.example.demo.model.UserInfo">
        <id column="id" jdbcType="INTEGER" property="id"/>
        <result column="user_name" jdbcType="VARCHAR" property="userName"/>
    </resultMap>

    <sql id="Base_Column_List">
      id,user_name
    </sql>

    <select id="selectById" parameterType="java.lang.Integer" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from user_info
        where id = #{id,jdbcType=VARCHAR}
    </select>

</mapper>
复制代码

Dao

package com.example.demo.dao;

import com.example.demo.model.UserInfo;
import org.apache.ibatis.annotations.Param;

/**
 * @author 张瑶
 * @Description:
 * @time 2018/4/18 11:54
 */
public interface UserInfoMapper {

    UserInfo selectById(@Param("id") Integer id);
}复制代码

Service

package com.example.demo.service;

import com.example.demo.model.UserInfo;

/**
 * @author 张瑶
 * @Description:
 * @time 2018/4/18 11:56
 */
public interface UserInfoService {

    UserInfo selectById(Integer id);

}复制代码

ServiceImpl

package com.example.demo.service.impl;

import com.example.demo.dao.UserInfoMapper;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserInfoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author 张瑶
 * @Description:
 * @time 2018/4/18 11:56
 */
@Service
public class UserInfoServiceImpl implements UserInfoService{

    @Resource
    private UserInfoMapper userInfoMapper;

    public UserInfo selectById(Integer id){
        return userInfoMapper.selectById(id);
    }
}复制代码

Controller

package com.example.demo.controller;

import com.example.demo.model.UserInfo;
import com.example.demo.service.UserInfoService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author 张瑶
 * @Description:
 * @time 2018/4/18 11:39
 */
@RestController
@RequestMapping("userInfo")
public class UserInfoController {

    @Resource
    private UserInfoService userInfoService;

    @PostMapping("/hello")
    public String hello(){
        return "hello SpringBoot";
    }

    @PostMapping("/selectById")
    public UserInfo selectById(Integer id){
        return userInfoService.selectById(id);
    }
}复制代码

Controller中@RestController注解的作用

@RestController是由@Controller和@ResponseBody组成,表示该类是controller和返回的结果为JSON数据,不是页面路径。

 

重点看一下configurer中的MyBatisConfigurer.java

package com.example.demo.core.configurer;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @ClassName: MybatisConfigurer
 * @Description: Mybatis配置
 * @author 张瑶
 * @date 2018年1月20日 下午4:03:46
 *
 */
@Configuration
public class MybatisConfigurer {

   @Bean
   public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
      SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
      factory.setDataSource(dataSource);
      factory.setTypeAliasesPackage("com.example.demo.model");
      // 添加XML目录
      ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
      factory.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
      return factory.getObject();
   }

   @Bean
   public MapperScannerConfigurer mapperScannerConfigurer() {
      MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
      mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
      mapperScannerConfigurer.setBasePackage("com.example.demo.dao");
      return mapperScannerConfigurer;
   }
}

@Configuration表示该文件是一个配置文件

@Bean表示该方法是一个传统xml配置文件中的<Bean id=""></Bean>

其中factory.setTypeAliasesPackage("com.example.demo.model")表示项目中model的存储路径;

factory.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));表示mapper.xml存储路径;

mapperScannerConfigurer.setBasePackage("com.example.demo.dao");表示dao层的存储路径

 

或者

# mybatis配置
mybatis.typeAliasesPackage=com.example.demo.domain
mybatis.mapperLocations=classpath:mapper/*.xml
package com.example.demo;

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

@SpringBootApplication
@MapperScan("com.example.demo.dao")
public class DemoApplication {

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

}

五:运行项目

找到DemoApplication,右键,选择run  DemoApplication

控制台打印如下信息即为启动成功

六:测试接口

打开postman(Google浏览器插件,可以去应用商店下载),输入

注意修改自己的ip;出现以下结构数据即访问成功

{
    "id": 1,
    "userName": "1"
}

项目地址

GitHub地址:

结尾

框架搭建,整合mybatis已完成,后续功能接下来陆续更新,有问题可以联系我13486032976@163.com。另求各路大神指点,感谢大家。

### 创建和运行基于Spring Boot、Vue和MyBatis-Plus的人事管理系统 #### 项目准备阶段 为了构建一个高效且易于维护的人事管理系统,在开始编码之前,需确保已准备好必要的开发环境。这包括但不限于安装最新版的IntelliJ IDEA以及配置好本地MySQL服务器[^1]。 #### 后端服务搭建 ##### 初始化Spring Boot工程 利用IntelliJ IDEA内置的支持快速建立一个新的Spring Initializr项目。选择`Maven`作为构建工具,并添加如下依赖项: - `Spring Web`: 提供RESTful API接口支持 - `Spring Data JPA`: 实现持久层操作简化 - `MyBatis Framework`: 数据库访问增强组件 - `Thymeleaf`: 虽然本案例前端采用Vue.js, Thymeleaf可用于页面模板渲染测试 - `MySQL Driver`: 连接并操作MySQL数据库所需驱动程序 完成上述设置后点击“Generate”,下载完成后导入至IDEA中继续后续工作。 ```xml <dependencies> <!-- Spring Boot Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MyBatis Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> </dependency> <!-- MySQL Connector --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> ... </dependencies> ``` ##### 配置数据源连接池 编辑application.properties文件以适配具体的MySQL实例参数: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/hr_management?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver ``` 此处假设数据库名为hr_management,请根据实际情况调整URL中的路径部分。 #### 前端应用建设 对于前端部分,推荐使用Vue CLI脚手架创建独立的应用目录结构。通过命令行执行vue create hr-front启动向导过程,挑选适合团队协作模式的基础选项即可满足需求。 之后借助Element UI这类UI框架加速界面布局设计进度;同时考虑引入axios发起HTTP请求与后台交互获取动态数据资源[^2]。 #### 整合前后端通信机制 考虑到跨域资源共享(CORS)问题的存在,可以在Spring Boot控制器类上加注解@EnableCrossOrigin允许特定域名下的客户端发送AJAX调用。另外还需注意JSON序列化格式统一处理方式的选择,比如FastJson或Jackson等第三方库辅助解析复杂对象实体映射关系。 最后一步就是将打包好的dist文件夹内容复制到Tomcat webapps根目录下指定位置,从而实现单页应用程序(SPA)加载地址重定向逻辑控制[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值