一、创建Spring Boot项目

参考:使用IntelliJ IDEA创建简单的Spring Boot项目

二、数据库、表的创建

三、项目开发

3.1 pom.xml文件配置

<?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.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yh</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency> <dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.1</version>
</dependency> <dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency> <dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.4</version>
</dependency> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

3.2 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="useGeneratedKeys" value="true"/>
<!--别名-->
<setting name="useColumnLabel" value="true"/>
<!--名称转换-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>

3.3 dao配置类datasource和sessionfactory

DataSourceConfiguration.java

package com.yh.demo.config.dao;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import java.beans.PropertyVetoException; @Configuration
// 配置mybaits的mapper扫描路径
@MapperScan("com.yh.demo.dao")
public class DataSourceConfiguration {
@Value("${jdbc.driver}")
private String jdbcDriver;
@Value("${jdbc.url}")
private String jdbcUrl;
@Value("${jdbc.username}")
private String jdbcUser;
@Value("${jdbc.password}")
private String jdbcPassword; @Bean("dataSource")
public ComboPooledDataSource createDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(jdbcDriver);
dataSource.setJdbcUrl(jdbcUrl);
dataSource.setUser(jdbcUser);
dataSource.setPassword(jdbcPassword);
// 配置c3p0连接池的私有属性
// 连接池最大线程数
dataSource.setMaxPoolSize(30);
// 连接池最小线程数
dataSource.setMinPoolSize(10);
// 连接池初始化连接数
dataSource.setInitialPoolSize(15);
// 关闭连接后不自动commit
dataSource.setAutoCommitOnClose(false);
return dataSource;
}
}

SessionFactoryConfiguration.java

package com.yh.demo.config.dao;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import javax.sql.DataSource;
import java.io.IOException; @Configuration
public class SessionFactoryConfiguration { @Value("${mybatis_config_file}")
private String mybatisConfigFilePath;
@Value("${entity_package}")
private String entityPackage;
@Value("${mapper_path}")
private String mapperPath; @Autowired
@Qualifier("dataSource")
private DataSource dataSource; @Bean("sqlSessionFactory")
public SqlSessionFactoryBean createFactory() throws IOException {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath));
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPath;
sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage);
return sqlSessionFactoryBean;
}
}

3.4 dao和mapper的编写

RunoobDao.java

package com.yh.demo.dao;

import com.yh.demo.entity.Runoob;

import java.util.List;

public interface RunoobDao {
List<Runoob> queryRunoob();
int insertRunoob(Runoob runoob);
}

RunoobDao.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.yh.demo.dao.RunoobDao">
<select id="queryRunoob" resultType="com.yh.demo.entity.Runoob">
select* from runoob_tbl
</select> <insert id="insertRunoob" parameterType="com.yh.demo.entity.Runoob">
insert into runoob_tbl(runoob_title)values (#{runoobTitle})
</insert>
</mapper>

3.5 service配置类TransactionManagementConfiguration

TransactionManagementConfiguration.java

package com.yh.demo.config.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer; import javax.sql.DataSource; @Configuration
@EnableTransactionManagement
public class TransactionManagementConfiguration implements TransactionManagementConfigurer { @Autowired
private DataSource dataSource; @Override
public TransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
}

3.6 service层接口和实现

RunoobService.java

package com.yh.demo.service;

import com.yh.demo.entity.Runoob;

import java.util.List;

public interface RunoobService {
List<Runoob> queryRunoob();
int insertRunoob(Runoob runoob);
}

RunoobServiceImpl.java

package com.yh.demo.service.serviceImpl;

import com.yh.demo.dao.RunoobDao;
import com.yh.demo.entity.Runoob;
import com.yh.demo.service.RunoobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service
public class RunoobServiceImpl implements RunoobService {
@Autowired
private RunoobDao runoobDao; @Override
public List<Runoob> queryRunoob() {
return runoobDao.queryRunoob();
} @Transactional
@Override
public int insertRunoob(Runoob runoob) {
return runoobDao.insertRunoob(runoob);
}
}

3.7 controller方法实现

RunoobController.java

package com.yh.demo.controller.data;

import com.yh.demo.entity.Runoob;
import com.yh.demo.service.RunoobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map; @RestController
@RequestMapping("/runoob")
public class RunoobController {
@Autowired
private RunoobService runoobService; @RequestMapping(value = "/query",method = RequestMethod.GET)
public Map<String,Object> queryRunoob(HttpServletResponse response){
response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
response.setHeader("Access-Control-Allow-Methods", "GET,POST");
Map<String,Object> modelMap = new HashMap<String,Object>();
List<Runoob> runoobs = runoobService.queryRunoob();
modelMap.put("runoobList",runoobs);
System.out.println("========");
return modelMap;
} @RequestMapping(value = "/insert",method = RequestMethod.POST)
public Map<String,Object> insertRunoob(@RequestBody Runoob runoob){
Map<String,Object> modelMap = new HashMap<String, Object>();
modelMap.put("success",runoobService.insertRunoob(runoob));
return modelMap;
}
}

四、其他文件

4.1 application.properties

server.port=8082
server.servlet.context-path=/demo jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=12345yehuan #mybatis
mybatis_config_file=mybatis-config.xml
mapper_path=/mapper/**.xml
entity_package=com.yh.demo.entity

4.2 实体类

Runoob.java

package com.yh.demo.entity;

public class Runoob {
private int runoobId;
private String runoobTitle; public int getRunoobId() {
return runoobId;
} public void setRunoobId(int runoobId) {
this.runoobId = runoobId;
} public String getRunoobTitle() {
return runoobTitle;
} public void setRunoobTitle(String runoobTitle) {
this.runoobTitle = runoobTitle;
} @Override
public String toString() {
return "Runoob{" +
"runoobId=" + runoobId +
", runoobTitle='" + runoobTitle + '\'' +
'}';
}
}

4.3 项目结构

五、dao测试

选定dao接口名 - alt+enter - create test -选择需要测试的方法,在test下的对应路径下就会生成对应的测试类,如下所示:

RunoobDaoTest.java

package com.yh.demo.dao;

import com.yh.demo.entity.Runoob;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import java.util.List; import static org.junit.jupiter.api.Assertions.*; @RunWith(SpringRunner.class)
@SpringBootTest
public class RunoobDaoTest { @Autowired
private RunoobDao runoobDao; @Test
public void queryRunoob() {
List<Runoob> runoobs = runoobDao.queryRunoob();
System.out.println(runoobs.toString());
assertEquals(1,runoobs.size());
} @Test
public void insertRunoob() {
Runoob runoob = new Runoob();
runoob.setRunoobTitle("第二条");
int result = runoobDao.insertRunoob(runoob);
assertEquals(1,result);
}
}

简单的Spring Boot项目——实现连接Mysql数据库的更多相关文章

  1. Docker 部署Spring Boot 项目并连接mysql、redis容器(记录过程)

    Spring Boot 项目配置 将写好的Spring Boot 项目通过maven 进行package打包获得可执行Jar 再src/main/docker(放哪都行)下编写创建Dockerfile ...

  2. 记录一次Spring boot 搭建框架连接Mysql数据库注解事务不回滚的故障

    搭建了一个新框架,使用了spring boot 替换以简化原来繁杂的spring配置,使用Spring注解管理事务,持久层使用mybatis. 连接mysql数据库完成项目的过程中发现不支持事务,因为 ...

  3. Spring Boot 项目学习 (二) MySql + MyBatis 注解 + 分页控件 配置

    0 引言 本文主要在Spring Boot 基础项目的基础上,添加 Mysql .MyBatis(注解方式)与 分页控件 的配置,用于协助完成数据库操作. 1 创建数据表 这个过程就暂时省略了. 2 ...

  4. 构建一个简单的Spring Boot项目

    11 构建一个简单的Spring Boot项目 这个章节描述如何通过Spring Boot构建一个"Hello Word"web应用,侧重介绍Spring Boot的一些重要功能. ...

  5. django新建项目,连接mysql数据库

    安装django,进入Django目录,运行 python setup.py install 在workplace目录下新建一个名为site01的项目: cd workplacedjango-admi ...

  6. Spring boot通过JPA访问MySQL数据库

    本文展示如何通过JPA访问MySQL数据库. JPA全称Java Persistence API,即Java持久化API,它为Java开发人员提供了一种对象/关系映射工具来管理Java应用中的关系数据 ...

  7. Spring Boot项目application.yml文件数据库配置密码加密

    在Spring boot开发中,需要在application.yml文件里配置数据库的连接信息,或者在启动时传入数据库密码,如果不加密,传明文,数据库就直接暴露了,相当于"裸奔"了 ...

  8. spring boot 集成mybatis连接oracle数据库

    1. POM文件添加依赖 <!-- Mybatis --> <dependency> <groupId>org.mybatis.spring.boot</gr ...

  9. PyCharm创建Django项目并连接mysql数据库

    0. 安装Django pip install django 1. 新建项目 注:我的Pycharm为社区版,创建项目时,File->New Project- 显示为: ​ 注意勾选内容. 如果 ...

随机推荐

  1. 史上最简单的排序算法?看起来却满是bug

    大家好,我是雨乐. 今天在搜论文的时候,偶然发现一篇文章,名为<Is this the simplest (and most surprising) sorting algorithm ever ...

  2. Python基础(类和实例)

    class Point(object): def __init__(self,name,score): self.__name = name self.__score = score def prin ...

  3. .NET GC 实时监控 dotnet-gcmon 介绍

    今天介绍一个新的诊断工具 dotnet-gcmon, 也是全局 .NET CLI 工具, 它可以监控到 .NET 程序的 GC, 能获取到的信息也很详细, 另外 maoni 大佬也是其中的开发者之一. ...

  4. PaintHouse II

    // // Created by Administrator on 2021/7/27. // #ifndef C__TEST01_PAINTHOUSE_HPP #define C__TEST01_P ...

  5. CF1511E Colorings and Dominoes

    考虑计数拆开贡献. 因为在一个方案中一个格子最多只会贡献一次,那么不妨反过来求这个格子贡献了多少次. 然后发现,行列独立,那么我们单独计算红蓝色,即可. 一个偶数块贡献当且仅当前面也是偶数块. 然后显 ...

  6. 【POJ1845】Sumdiv【算数基本定理 + 逆元】

    描述 Consider two natural numbers A and B. Let S be the sum of all natural divisors of A^B. Determine ...

  7. 【2020五校联考NOIP #8】自闭

    题目传送门 题意: 有一个 \(n \times m\) 的矩阵,里面已经填好了 \(k\) 个非负整数. 问是否能在其它 \(n \times m-k\) 个格子里各填上一个非负整数,使得得到的矩阵 ...

  8. 洛谷 P5044 - [IOI2018] meetings 会议(笛卡尔树+DP+线段树)

    洛谷题面传送门 一道笛卡尔树的 hot tea. 首先我们考虑一个非常 naive 的区间 DP:\(dp_{l,r}\) 表示区间 \([l,r]\) 的答案,那么我们考虑求出 \([l,r]\) ...

  9. Atcoder Grand Contest 001E - BBQ Hard(组合意义转化,思维题)

    Atcoder 题面传送门 & 洛谷题面传送门 Yet another 思维题-- 注意到此题 \(n\) 数据范围很大,但是 \(a_i,b_i\) 数据范围很小,这能给我们什么启发呢? 观 ...

  10. Codeforces 983E - NN country(贪心+倍增优化)

    Codeforces 题面传送门 & 洛谷题面传送门 一道(绝对)偏简单的 D1E,但是我怕自己过若干年(大雾)忘了自己的解法了,所以过来水篇题解( 首先考虑怎么暴力地解决这个问题,不难发现我 ...