本案例所使用到的IDE
jdk1.8、MySQL5.7
一、新建Maven项目
请参考我关于SpringBoot教程的第一讲内容:
https://blog.csdn.net/qzc70919700/article/details/119574690
二、配置pom.xml文件
2.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 http://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>1.5.2.RELEASE</version>
</parent>
<groupId>cn.personal.qin.demo</groupId>
<artifactId>springboot_demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>springboot</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- java版本 -->
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!-- 添加springMVC支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
<!-- dbcp连接池 <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId>
<version>1.4</version> </dependency> -->
<!-- 连接池 -->
<dependency>
<groupId>com.jolbox</groupId>
<artifactId>bonecp-spring</artifactId>
<version>0.8.0.RELEASE</version>
</dependency>
<!-- spring核心 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<!-- Begin##添加JSP支持##Begin -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<!-- End##添加JSP支持##Begin -->
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<!-- 资源文件拷贝插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- java编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- Begin##03、添加SpringBoot的插件支持##Begin -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- End##03、添加SpringBoot的插件支持##End -->
</plugins>
<pluginManagement>
<plugins>
<!-- 配置Tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
2.2、更新Maven下载jar包
项目鼠标右键-->Maven-->Update Project...
三、项目开发
3.1、项目文件结构
请下载项目源代码,并将配置文件拷贝到src/main/resources文件夹中
?3.2、配置MyBatis
3.2.1、MyBatis目录配置类Cast
Cast.java类的作用是用于配置MyBatis中配置文件及mapper、po的位置
package org.personal.qin.demo.config;
public class Cast {
//配置MyBatis
public static final String MYBATIS_CONFIG = "classpath:mybatis-config.xml";
public static final String PO_PACKAGE = "org.personal.qin.demo.po";
public static final String MAPPER_PACKAGE = "org.personal.qin.demo.mapper";
public static final String MAPPER_SCANNER = "classpath:config/mapper/*.xml";
}
3.2.2、MyBatis加载配置文件及配置数据源MyBatisConfig
MyBatisConfig.java类的作用是加载MyBatis配置文件,并配置数据源
package org.personal.qin.demo.config;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
@Configuration
public class MyBatisConfig {
/**
* ConditionalOnMissingBean当容器里没有指定的Bean的情况下创建该对象
*/
@Bean
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
// 设置数据源
sqlSessionFactoryBean.setDataSource(dataSource);
// 添加一行如下代码,解决setTypeAliasesPackage别名设置不起作用问题
sqlSessionFactoryBean.setVfs(SpringBootVFS.class);
//设置mybatis的主配置文件
ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
Resource mybatisConfigXml = resourceResolver.getResource(Cast.MYBATIS_CONFIG);
sqlSessionFactoryBean.setConfigLocation(mybatisConfigXml);
// 设置别名包
sqlSessionFactoryBean.setTypeAliasesPackage(Cast.PO_PACKAGE);
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources(Cast.MAPPER_SCANNER));
return sqlSessionFactoryBean.getObject();
}
}
3.2.3、Mapper扫描MapperScannerConfig
MapperScannerConfig.java类的作用是扫描Mapper
package org.personal.qin.demo.config;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 保证在MybatisConfig类实例化后才实例化此方法
*/
@Configuration
@AutoConfigureAfter(MyBatisConfig.class)
public class MapperScannerConfig {
/**
* mapper接口的扫描器
*
* @return
*/
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage(Cast.MAPPER_PACKAGE);
return mapperScannerConfigurer;
}
}
3.3、配置SpringBoot
BootApplication.java文件的作用是配置SpringBoot,并加载jdbc配置文件,配置数据库及数据库连接池,MainApplication.java提供了main方法,是该程序的入口以供程序运行
package org.personal.qin.demo.config;
import javax.sql.DataSource;
import com.jolbox.bonecp.BoneCPDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
* 配置文件读取和扫描
*/
@Configuration
@PropertySource(value = { "classpath:jdbc.properties" })
@ComponentScan(basePackages = "org.personal.qin.demo")
@SpringBootApplication
public class BootApplication {
@Value("${jdbc.driver}")
private String driverClassName; // 数据库驱动
@Value("${jdbc.url}")
private String url; // 相应驱动的jdbcUrl
@Value("${jdbc.username}")
private String username; // 数据库的用户名
@Value("${jdbc.password}")
private String password; // 数据库的密码
@Value("${jdbc.period_in_minutes}")
private int periodInMinutes; // 检查数据库连接池中空闲连接的间隔时间,单位是分,默认值:240,如果要取消则设置为0
@Value("${jdbc.max_age_in_minutes}")
private int maxAgeInMinutes; // 连接池中未使用的链接最大存活时间,单位是分,默认值:60,如果要永远存活设置为0
@Value("${jdbc.max_connections_per_partition}")
private int maxConnectionsPerPartition; // 每个分区最大的连接数
@Value("${jdbc.min_connections_per_partition}")
private int minConnectionsPerPartition; // 每个分区最小的连接数
/**
* 配置数据源
*
* @return
*/
@Bean(destroyMethod = "close")
public DataSource dataSource() {
BoneCPDataSource boneCPDataSource = new BoneCPDataSource();
boneCPDataSource.setDriverClass(driverClassName);
boneCPDataSource.setJdbcUrl(url);
boneCPDataSource.setUsername(username);
boneCPDataSource.setPassword(password);
boneCPDataSource.setIdleConnectionTestPeriodInMinutes(periodInMinutes);
boneCPDataSource.setIdleMaxAgeInMinutes(maxAgeInMinutes);
boneCPDataSource.setMaxConnectionsPerPartition(maxConnectionsPerPartition);
boneCPDataSource.setMinConnectionsPerPartition(minConnectionsPerPartition);
return boneCPDataSource;
}
protected SpringApplicationBuilder springApplicationBuilder(SpringApplicationBuilder builder) {
return builder.sources(BootApplication.class);
}
}
package org.personal.qin.demo;
import org.personal.qin.demo.config.BootApplication;
import org.springframework.boot.SpringApplication;
/**
* 项目工程入口
*/
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(BootApplication.class, args);
}
}
3.4、开始业务层代码
开始编写业务层代码Po、Mapper、Controller
3.4.1、Po
User.java是Pojo
package org.personal.qin.demo.po;
public class User {
private int id;
private String name;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "【User】: name=" + name + ", password=" + password;
}
}
3.4.2、Mapper
UserMapper.java是Mapper接口,UserMapper.xml是操作数据库的配置文件
package org.personal.qin.demo.mapper;
import java.util.List;
import org.personal.qin.demo.po.User;
public interface UserMapper {
/**
* 获取全部用户
*
* @return
*/
List<User> listAll();
}
<?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.personal.qin.demo.mapper.UserMapper">
<select id="listAll" resultType="User">
select * from t_user
</select>
</mapper>
3.4.3、Controller
UserController.java是控制器,提供给web访问
package org.personal.qin.demo.controller;
import java.util.List;
import org.personal.qin.demo.mapper.UserMapper;
import org.personal.qin.demo.po.User;
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;
@Controller
public class UserController {
@Autowired
private UserMapper mapper;
@RequestMapping("/users")
@ResponseBody
public Object getAllUser() {
List<User> users = mapper.listAll();
return users;
}
}
四、浏览器测试
运行MainApplication.java中的main方法
浏览器中访问UserController的/users映射:http://127.0.0.1:8080/users
?成功从数据库中读取到了数据,并以json的格式显示在了网页上
五、项目源代码及数据库脚本
https://download.csdn.net/download/qzc70919700/20970559???????
|