SpringBoot + SqlServer+Mybatis

Java架构技术进阶

共 9873字,需浏览 20分钟

 ·

2021-03-13 02:01

前提:项目搭建需要数据库,运行这个项目之前需要先部署好sqlserver数据库,上一篇文章简单的用docker部署了sqlserver数据库,有需要的可以去看下:Docker安装部署Sql Server

maven引入

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.jeemp</groupId>
<artifactId>jeemp-sqlserver</artifactId>
<version>1.0.0</version>
<name>jeemp-sqlserver</name>
<description>Demo project for Spring Boot</description>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

application.properties配置


#端口号
server.port=8083
#上下文
server.servlet.context-path=/jeemp

#sql server jdbc配置
spring.datasource.url=jdbc:sqlserver://172.16.10.54:1433;DatabaseName=jeemp
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.username=sa
spring.datasource.password=Root123456

#开发环境配置mapper层开启debug模式打印sql调用,其他环境不要
logging.level.org.jeemp.sqlserver.dao=debug
#数据库mapper文件路径
mybatis.mapper-locations=classpath:mapper/**/*.xml
#指定POJO扫描包来让mybatis自动扫描到自定义POJO
mybatis.type-aliases-package=org.jeemp.sqlserver.entity

#hikari数据库连接池配置
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.maximum-pool-size=15
spring.datasource.hikari.auto-commit=true
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.pool-name=DatebookHikariCP
spring.datasource.hikari.max-lifetime=900000
spring.datasource.hikari.connection-timeout=15000
spring.datasource.hikari.connection-test-query=SELECT 1

创建User

package org.jeemp.sqlserver.entity.po;

import lombok.Data;

import java.sql.Timestamp;

/**
* @author: xueshan.zeng
* @date: 2019/8/7
*/

@Data
public class User {
private int userId;
private String username;
private String password;
private Timestamp createTime;
private Timestamp updateTime;
}

创建UserMapper

package org.jeemp.sqlserver.dao;

import org.jeemp.sqlserver.entity.po.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
* @author JackRen
* @date 2021/3/11
*
**/

@Mapper
public interface UserMapper {
/**
* 获取User信息
*
* @param pageStart 起始页码
* @param pageEnd 结束页码
* @param fetchAll 是否查询全部
* @return User信息
*/

List<User> selectModels(int pageStart, int pageEnd, boolean fetchAll);
/**
* 获取User信息个数
*
* @return User信息个数
*/

int selectCount();

void insertUser(User user);

int updateUserById(User user);
}

创建Service

package org.jeemp.sqlserver.service.impl;

import org.jeemp.sqlserver.dao.UserMapper;
import org.jeemp.sqlserver.entity.bo.BasePage;
import org.jeemp.sqlserver.entity.dto.UserInfoParamsDTO;
import org.jeemp.sqlserver.entity.po.User;
import org.jeemp.sqlserver.entity.vo.UserInfoExport;
import org.jeemp.sqlserver.service.IUserService;
import org.jeemp.sqlserver.utils.StringConvertUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
* @author JackRen
* @date 2021/3/11
*
**/

@Service("userService")
public class UserServiceImpl implements IUserService {
private static final String ONE = "1";

@Resource
private UserMapper userMapper;

@Override
public UserInfoExport getUserInfo(UserInfoParamsDTO userInfoParamsDTO) {
checkParams(userInfoParamsDTO);

BasePage basePage = StringConvertUtils.transferBasePage(userInfoParamsDTO.getPageIndex(), userInfoParamsDTO.getPageSize());
List<User> users = userMapper.selectModels(basePage.getPageStart(), basePage.getPageEnd(), ONE.equals(userInfoParamsDTO.getFetchAll()));
int total = userMapper.selectCount();

return new UserInfoExport(users, total + "");
}

@Override
public void getUserData(User user) {
userMapper.insertUser(user);
}

@Override
public void updateUserById(User user) {
int ret = userMapper.updateUserById(user);
System.out.println(ret);
}

private void checkParams(UserInfoParamsDTO userInfoParamsDTO) {
try{
Long.parseLong(userInfoParamsDTO.getPageIndex());
Long.parseLong(userInfoParamsDTO.getPageSize());
}catch (Exception e){
throw new RuntimeException("请求不合法");
}
}
}

创建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="org.jeemp.sqlserver.dao.UserMapper">
<resultMap id="BaseResultMap" type="org.jeemp.sqlserver.entity.po.User">
<result column="user_id" jdbcType="NUMERIC" property="userId" />
<result column="username" jdbcType="VARCHAR" property="username" />
<result column="password" jdbcType="VARCHAR" property="password" />
<result column="create_time" jdbcType="VARCHAR" property="createTime" />
<result column="update_time" jdbcType="VARCHAR" property="updateTime" />
</resultMap>
<sql id="selectModelsSql">
select user_id,username,password,create_time,update_time,ROW_NUMBER() OVER (ORDER BY user_id ASC) as rn from [user]
</sql>
<select id="selectModels" resultMap="BaseResultMap">
select a.*
from (
<include refid="selectModelsSql"></include>
) a
<if test="fetchAll == false">
where a.rn <![CDATA[>=]]> #{pageStart,jdbcType=INTEGER} and a.rn <![CDATA[<=]]> #{pageEnd,jdbcType=INTEGER}
</if>
</select>
<select id="selectCount" resultType="int">
select count(*)
from (
<include refid="selectModelsSql"></include>
) a
</select>

<insert id="insertUser" parameterType="org.jeemp.sqlserver.entity.po.User">
insert into [user](user_id,username,password,create_time,update_time)values(#{userId},#{username},#{password},#{createTime},#{updateTime})
</insert>

<update id="updateUserById">
update user
<set>
<if test="username != null">username=#{username}, </if>
<if test="password != null">password=#{password}, </if>
<if test="createTime != null">create_time=#{createTime}, </if>
<if test="updateTime != null">update_time=#{updateTime}, </if>
</set>
where user_id=#{userId}
</update>

</mapper>

Controller类

package org.jeemp.sqlserver.controller;

import org.jeemp.sqlserver.entity.dto.UserInfoParamsDTO;
import org.jeemp.sqlserver.entity.po.User;
import org.jeemp.sqlserver.service.IUserService;
import org.jeemp.sqlserver.utils.IdUtil;
import org.jeemp.sqlserver.utils.SnowflakeUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;

/**
* @author JackRen
* @date 2021/3/11
*
**/

@RestController
public class UserController {
@Resource
private IUserService userService;

@GetMapping("userInfo")
public Object getUserInfo(String pageIndex, String pageSize, String fetchAll){
UserInfoParamsDTO userInfoParamsDTO = new UserInfoParamsDTO(pageIndex,pageSize,fetchAll);
return userService.getUserInfo(userInfoParamsDTO);
}

@GetMapping("insertUserData")
public void getUserData() {
User user = new User();
user.setUserId((int) SnowflakeUtil.nextId());
user.setUsername(IdUtil.uuid());
user.setPassword("123456");
Date date = new Date();
user.setCreateTime(new Timestamp(date.getTime()));
user.setUpdateTime(new Timestamp(date.getTime()));
userService.getUserData(user);
}

@PostMapping("updateUserData")
public void updateUserById(@RequestBody User user) {
userService.updateUserById(user);
}

}

验证测试

插入方法调用:
http://localhost:8083/jeemp/insertUserData


查询调用



浏览 63
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报