Springboot 整合Mybatis,用模板引擎thymeleaf,實現數據庫的連接
這裏寫的是Springboot整合Mybatis實現一個最基本的增刪改查功能,整合的方式有兩種一種是註解形式的,也就是沒有Mapper.xml文件,還有一種是XML形式的,這裏寫的是整合mybaits 寫入xml方式
註解版:https://baijiahao.baidu.com/s?id=1653043822915271722&wfr=spider&for=pc
目錄:
1、配置pom.xml
<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>com.springboot</groupId>
<artifactId>parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>Mybaris</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 數據庫驅動座標 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<!-- alibaba的druid的數據庫連接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.11</version>
</dependency>
<!-- 分頁插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.1.2</version>
</dependency>
<!--thymeleaf啓動器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- Druid數據源依賴 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
</dependencies>
</project>
2、配置application.yml
spring:
mvc:
static-path-pattern: /**
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/mobiledb?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
username: root
password: 123456
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
connection-properties: druid.stat.mergeSql:true;druid.stat.slowSqlMillis:5000
thymeleaf:
cache: false
content-type: text/html
check-template-location: true
mode: LEGACYHTML5
enabled: true
prefix: classpath:/templates/
suffix: .html
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
mybatis:
mapper-locations: classpath:mappers/UsersMapper.xml
config-location: classpath:mybatis/mybatis-config.xml
templates-locations: templates/addUser.html
3、配置mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!--適應駝峯-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
4、運用逆向工程生成的相關代碼:
Users.java
package com.mall.pojo;
public class Users {
private String user;
private Long currentConnections;
private Long totalConnections;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user == null ? null : user.trim();
}
public Long getCurrentConnections() {
return currentConnections;
}
public void setCurrentConnections(Long currentConnections) {
this.currentConnections = currentConnections;
}
public Long getTotalConnections() {
return totalConnections;
}
public void setTotalConnections(Long totalConnections) {
this.totalConnections = totalConnections;
}
private Integer userid;
private String username;
private String usersex;
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
public String getUsersex() {
return usersex;
}
public void setUsersex(String usersex) {
this.usersex = usersex == null ? null : usersex.trim();
}
}
UsersMapper.java
package com.mall.mapper;
import com.mall.pojo.Users;
public interface UsersMapper {
int insert(Users record);
int insertSelective(Users record);
int deleteByPrimaryKey(Integer userid);
Users selectByPrimaryKey(Integer userid);
int updateByPrimaryKeySelective(Users record);
int updateByPrimaryKey(Users record);
}
UsersMapper.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.mall.mapper.UsersMapper">
<resultMap id="BaseResultMap" type="com.mall.pojo.Users">
<result column="USER" jdbcType="CHAR" property="user" />
<result column="CURRENT_CONNECTIONS" jdbcType="BIGINT" property="currentConnections" />
<result column="TOTAL_CONNECTIONS" jdbcType="BIGINT" property="totalConnections" />
</resultMap>
<sql id="Base_Column_List">
userid, username, usersex
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from users
where userid = #{userid,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from users
where userid = #{userid,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.mall.pojo.Users">
insert into users (userid, username, usersex
)
values (#{userid,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{usersex,jdbcType=VARCHAR}
)
</insert>
<insert id="insertSelective" parameterType="com.mall.pojo.Users">
insert into users
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="userid != null">
userid,
</if>
<if test="username != null">
username,
</if>
<if test="usersex != null">
usersex,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="userid != null">
#{userid,jdbcType=INTEGER},
</if>
<if test="username != null">
#{username,jdbcType=VARCHAR},
</if>
<if test="usersex != null">
#{usersex,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.mall.pojo.Users">
update users
<set>
<if test="username != null">
username = #{username,jdbcType=VARCHAR},
</if>
<if test="usersex != null">
usersex = #{usersex,jdbcType=VARCHAR},
</if>
</set>
where userid = #{userid,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.mall.pojo.Users">
update users
set username = #{username,jdbcType=VARCHAR},
usersex = #{usersex,jdbcType=VARCHAR}
where userid = #{userid,jdbcType=INTEGER}
</update>
</mapper>
5、業務層接口
package com.mall.services;
import java.util.List;
import com.mall.pojo.Users;
public interface UsersService {
void addUser(Users users);
List<Users> selectUserall();
Users selectUserid(Integer id);
void updataUser(Users users);
void deleteUser(Integer id);
}
業務層實現類
package com.mall.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mall.mapper.UsersMapper;
import com.mall.pojo.Users;
/**
*
* 用戶管理業務層
*
*/
@Service
public class UserServiceImpl implements UsersService {
@Autowired
private UsersMapper usersMapper;
/**
* 添加用戶
*/
@Override
@Transactional
public void addUser(Users users) {
this.usersMapper.insert(users);
}
/**
* 查詢所有用戶
*/
@Override
public List<Users> selectUserall() {
return null;
}
/**
* 預更新
*/
@Override
public Users selectUserid(Integer id) {
// TODO Auto-generated method stub
return this.usersMapper.selectByPrimaryKey(id);
}
/**更新
*
*/
@Override
public void updataUser(Users users) {
this.usersMapper.updateByPrimaryKey(users);
}
@Override
public void deleteUser(Integer id) {
this.usersMapper.deleteByPrimaryKey(id);
}
}
6、Controller 控制層
跳轉頁面:
package com.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
/**
* 頁面跳轉
*
*
*/
public class pageController {
@RequestMapping("/{page}")
public String showPage(@PathVariable String page) {
return page;
}
}
控制頁面:
package com.Controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.mall.pojo.Users;
import com.mall.services.UsersService;
@Controller
@RequestMapping("/user")
public class Usercontroller {
@Autowired
private UsersService usersService;
/**
* 添加用戶
* @return
*/
@PostMapping("/addUser")
public String showInfo(Users users) {
try {
System.out.println("11111111111111");
this.usersService.addUser(users);
System.out.println("3333333333333333");
}catch (Exception e) {
e.printStackTrace();
System.out.println("3444444");
return "error";
}
return "redirect:/OK";
}
/**
* 查詢用戶
* @return
*/
@GetMapping("/selectUserall")
public String selectInfo(Model model) {
List<Users> list=null;
try {
list=this.usersService.selectUserall();
model.addAttribute("list",list);
}catch (Exception e) {
e.printStackTrace();
return "error";
}
return "showUsers";
}
/**
* 預更新用戶
* @return
*/
@GetMapping("/selectUserid")
public String selectid(Integer id,Model model) {
try {
Users user=this.usersService.selectUserid(id);
model.addAttribute("user", user);
}catch (Exception e) {
e.printStackTrace();
return "error";
}
return "updataUser";
}
/**
* 更新用戶
* @return
*/
@PostMapping("/updataUser")
public String updataUser(Users users) {
try {
this.usersService.updataUser(users);
}catch (Exception e) {
e.printStackTrace();
return "error";
}
return "redirect:/OK";
}
/**
* 刪除用戶
* @return
*/
@GetMapping("/delectUser")
public String delectUser(Integer id) {
try {
this.usersService.deleteUser(id);
}catch (Exception e) {
e.printStackTrace();
return "error";
}
return "redirect:/OK";
}
}
7、啓動類
package Test;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages={"com.Controller","com.mall.services","com.mall.pojo"})
@MapperScan(basePackages = {"com.mall.mapper"})
public class Test {
public static void main(String[] args) {
SpringApplication.run(Test.class, args);
}
}
運行完成