最近在学习springboot.
Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。
--------------以上来自百度百科
总之,springboot 还是值得好好学习的,毕竟它比spring 少了 很麻烦的配置以及依赖,尤其是pom文件中引入maven依赖的时候很简洁。
下面我来搭建一个简单的springbooot+mybatis 项目,期间也遇到了一些问题,做一下记录和整理:
一。环境
1.开发工具: idea 2018.1.5
2.springboot版本: 2.0.8.RELEASE
二。开始创建一个工程
1.new --> Project
选择 Spring Initializr 下一步
填写相应的工程名及包名,下一步
选择需要用到的组件,因为是 我这里选择了 web,mysql和mybatis 下一步
选择finish
使用新窗口打开
二。后续工作
1.先修改maven的设置,下载maven jar包
这一步我就不贴图了。
2.下面我们来看一下pom文件
<?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 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>2.0.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.taoj</groupId>
<artifactId>springboot_mybatis07</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot_mybatis07</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.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
其中引入了web的起步依赖,mybatis和mysql的起步依赖,还有测试test的起步依赖。
接下来我们来看一下项目的结构:
其中有一个启动类 SpringbootMybatis07Application 通常我们可以直接启动一下我们这个启动类,我们来启动一下,
在启动过程中 控制台输出这个图标:
表示是springboot的项目,但是后面报错了。
"C:\Program Files (x86)\Java\jdk1.8.0_171\bin\java.exe" -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=61815 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=localhost -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true "-javaagent:H:\java_2018\idea\JetBrains\IntelliJ IDEA 2018.1.5\lib\idea_rt.jar=61816:H:\java_2018\idea\JetBrains\IntelliJ IDEA 2018.1.5\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\charsets.jar;C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\deploy.jar;C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\ext\access-bridge-64.jar;C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\ext\cldrdata.jar;C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\ext\dnsns.jar;C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\ext\jaccess.jar;C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\ext\jfxrt.jar;C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\ext\localedata.jar;C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\ext\nashorn.jar;C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\ext\sunec.jar;C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\ext\sunjce_provider.jar;C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\ext\sunmscapi.jar;C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\ext\sunpkcs11.jar;C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\ext\zipfs.jar;C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\javaws.jar;C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\jce.jar;C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\jfr.jar;C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\jfxswt.jar;C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\jsse.jar;C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\management-agent.jar;C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\plugin.jar;C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\resources.jar;C:\Program Files (x86)\Java\jdk1.8.0_171\jre\lib\rt.jar;I:\TYWorkspace\study\Resource\02springboot_test02\springboot_mybatis07\target\classes;H:\apache_maven\local_repository\org\springframework\boot\spring-boot-starter-web\2.0.8.RELEASE\spring-boot-starter-web-2.0.8.RELEASE.jar;H:\apache_maven\local_repository\org\springframework\boot\spring-boot-starter\2.0.8.RELEASE\spring-boot-starter-2.0.8.RELEASE.jar;H:\apache_maven\local_repository\org\springframework\boot\spring-boot\2.0.8.RELEASE\spring-boot-2.0.8.RELEASE.jar;H:\apache_maven\local_repository\org\springframework\boot\spring-boot-autoconfigure\2.0.8.RELEASE\spring-boot-autoconfigure-2.0.8.RELEASE.jar;H:\apache_maven\local_repository\org\springframework\boot\spring-boot-starter-logging\2.0.8.RELEASE\spring-boot-starter-logging-2.0.8.RELEASE.jar;H:\apache_maven\local_repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;H:\apache_maven\local_repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;H:\apache_maven\local_repository\org\apache\logging\log4j\log4j-to-slf4j\2.10.0\log4j-to-slf4j-2.10.0.jar;H:\apache_maven\local_repository\org\apache\logging\log4j\log4j-api\2.10.0\log4j-api-2.10.0.jar;H:\apache_maven\local_repository\org\slf4j\jul-to-slf4j\1.7.25\jul-to-slf4j-1.7.25.jar;H:\apache_maven\local_repository\javax\annotation\javax.annotation-api\1.3.2\javax.annotation-api-1.3.2.jar;H:\apache_maven\local_repository\org\yaml\snakeyaml\1.19\snakeyaml-1.19.jar;H:\apache_maven\local_repository\org\springframework\boot\spring-boot-starter-json\2.0.8.RELEASE\spring-boot-starter-json-2.0.8.RELEASE.jar;H:\apache_maven\local_repository\com\fasterxml\jackson\core\jackson-databind\2.9.8\jackson-databind-2.9.8.jar;H:\apache_maven\local_repository\com\fasterxml\jackson\core\jackson-annotations\2.9.0\jackson-annotations-2.9.0.jar;H:\apache_maven\local_repository\com\fasterxml\jackson\core\jackson-core\2.9.8\jackson-core-2.9.8.jar;H:\apache_maven\local_repository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.9.8\jackson-datatype-jdk8-2.9.8.jar;H:\apache_maven\local_repository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.9.8\jackson-datatype-jsr310-2.9.8.jar;H:\apache_maven\local_repository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.9.8\jackson-module-parameter-names-2.9.8.jar;H:\apache_maven\local_repository\org\springframework\boot\spring-boot-starter-tomcat\2.0.8.RELEASE\spring-boot-starter-tomcat-2.0.8.RELEASE.jar;H:\apache_maven\local_repository\org\apache\tomcat\embed\tomcat-embed-core\8.5.37\tomcat-embed-core-8.5.37.jar;H:\apache_maven\local_repository\org\apache\tomcat\embed\tomcat-embed-el\8.5.37\tomcat-embed-el-8.5.37.jar;H:\apache_maven\local_repository\org\apache\tomcat\embed\tomcat-embed-websocket\8.5.37\tomcat-embed-websocket-8.5.37.jar;H:\apache_maven\local_repository\org\hibernate\validator\hibernate-validator\6.0.14.Final\hibernate-validator-6.0.14.Final.jar;H:\apache_maven\local_repository\javax\validation\validation-api\2.0.1.Final\validation-api-2.0.1.Final.jar;H:\apache_maven\local_repository\org\jboss\logging\jboss-logging\3.3.2.Final\jboss-logging-3.3.2.Final.jar;H:\apache_maven\local_repository\com\fasterxml\classmate\1.3.4\classmate-1.3.4.jar;H:\apache_maven\local_repository\org\springframework\spring-web\5.0.12.RELEASE\spring-web-5.0.12.RELEASE.jar;H:\apache_maven\local_repository\org\springframework\spring-beans\5.0.12.RELEASE\spring-beans-5.0.12.RELEASE.jar;H:\apache_maven\local_repository\org\springframework\spring-webmvc\5.0.12.RELEASE\spring-webmvc-5.0.12.RELEASE.jar;H:\apache_maven\local_repository\org\springframework\spring-aop\5.0.12.RELEASE\spring-aop-5.0.12.RELEASE.jar;H:\apache_maven\local_repository\org\springframework\spring-context\5.0.12.RELEASE\spring-context-5.0.12.RELEASE.jar;H:\apache_maven\local_repository\org\springframework\spring-expression\5.0.12.RELEASE\spring-expression-5.0.12.RELEASE.jar;H:\apache_maven\local_repository\org\mybatis\spring\boot\mybatis-spring-boot-starter\2.0.0\mybatis-spring-boot-starter-2.0.0.jar;H:\apache_maven\local_repository\org\springframework\boot\spring-boot-starter-jdbc\2.0.8.RELEASE\spring-boot-starter-jdbc-2.0.8.RELEASE.jar;H:\apache_maven\local_repository\com\zaxxer\HikariCP\2.7.9\HikariCP-2.7.9.jar;H:\apache_maven\local_repository\org\springframework\spring-jdbc\5.0.12.RELEASE\spring-jdbc-5.0.12.RELEASE.jar;H:\apache_maven\local_repository\org\springframework\spring-tx\5.0.12.RELEASE\spring-tx-5.0.12.RELEASE.jar;H:\apache_maven\local_repository\org\mybatis\spring\boot\mybatis-spring-boot-autoconfigure\2.0.0\mybatis-spring-boot-autoconfigure-2.0.0.jar;H:\apache_maven\local_repository\org\mybatis\mybatis\3.5.0\mybatis-3.5.0.jar;H:\apache_maven\local_repository\org\mybatis\mybatis-spring\2.0.0\mybatis-spring-2.0.0.jar;H:\apache_maven\local_repository\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar;H:\apache_maven\local_repository\org\slf4j\slf4j-api\1.7.25\slf4j-api-1.7.25.jar;H:\apache_maven\local_repository\org\springframework\spring-core\5.0.12.RELEASE\spring-core-5.0.12.RELEASE.jar;H:\apache_maven\local_repository\org\springframework\spring-jcl\5.0.12.RELEASE\spring-jcl-5.0.12.RELEASE.jar" com.taoj.SpringbootMybatis07Application
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.8.RELEASE)
2019-01-29 16:06:20.594 INFO 9220 --- [ main] com.taoj.SpringbootMybatis07Application : Starting SpringbootMybatis07Application on DESKTOP-VUUV0KL with PID 9220 (I:\TYWorkspace\study\Resource\02springboot_test02\springboot_mybatis07\target\classes started by 蒋涛 in I:\TYWorkspace\study\Resource\02springboot_test02\springboot_mybatis07)
2019-01-29 16:06:20.605 INFO 9220 --- [ main] com.taoj.SpringbootMybatis07Application : No active profile set, falling back to default profiles: default
2019-01-29 16:06:20.772 INFO 9220 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@4387b79e: startup date [Tue Jan 29 16:06:20 CST 2019]; root of context hierarchy
2019-01-29 16:06:21.769 WARN 9220 --- [ main] o.m.s.mapper.ClassPathMapperScanner : No MyBatis mapper was found in '[com.taoj]' package. Please check your configuration.
2019-01-29 16:06:22.983 INFO 9220 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-01-29 16:06:23.020 INFO 9220 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-01-29 16:06:23.020 INFO 9220 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.37
2019-01-29 16:06:23.025 INFO 9220 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files (x86)\Java\jdk1.8.0_171\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Program Files (x86)\Common Files\NetSarang;C:\ProgramData\Oracle\Java\javapath;H:\DBServer\oracle\OracleClient\oracle\product\10.2.0\client_1\bin;H:\DBServer\oracle\oracle11\app\蒋涛\product\11.2.0\dbhome_1\bin;C;\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\Java\jdk1.7.0_67\bin;H:\android-sdk-windows\build-tools\22.0.1;H:\android-sdk-windows\tools;H:\android-sdk-windows\platform-tools;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;H:\SVN\bin;H:\apache_maven\apache-maven-3.5.3\bin;G:\software\git\cmd;G:\software\TortoiseGit\bin;C:\Program Files (x86)\Common Files\Apple\Internet Services\;C:\Users\蒋涛\AppData\Local\GitHubDesktop\bin;%USERPROFILE%\AppData\Local\Microsoft\WindowsApps;;.]
2019-01-29 16:06:23.206 INFO 9220 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-01-29 16:06:23.207 INFO 9220 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2447 ms
2019-01-29 16:06:23.313 INFO 9220 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2019-01-29 16:06:23.319 INFO 9220 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2019-01-29 16:06:23.319 INFO 9220 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2019-01-29 16:06:23.320 INFO 9220 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2019-01-29 16:06:23.320 INFO 9220 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2019-01-29 16:06:23.570 INFO 9220 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-01-29 16:06:23.914 INFO 9220 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@4387b79e: startup date [Tue Jan 29 16:06:20 CST 2019]; root of context hierarchy
2019-01-29 16:06:24.018 INFO 9220 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2019-01-29 16:06:24.020 INFO 9220 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2019-01-29 16:06:24.058 INFO 9220 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-01-29 16:06:24.058 INFO 9220 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-01-29 16:06:24.147 WARN 9220 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
2019-01-29 16:06:24.151 INFO 9220 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2019-01-29 16:06:24.179 INFO 9220 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-01-29 16:06:24.187 ERROR 9220 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
Process finished with exit code 1
报错原因为:因为我们引入了mybatis 需要配置一下数据库的一些信息
如果我们没有引入mybatis的组件,我们就可以直接启动,并且可以编写controller, 现在要需要添加数据库的配置信息,我们在resources下面新建一个application.yml文件。我们看到已经有一个application.properties文件了,为什么不用这个文件进行配置呢,原因可以自行查询。既然使用了springboot ,咱们就学点新的东西,application.yml文件配置更加的简洁。
接下来贴出application.yml 中的内容:
# 配置数据源
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
driver-class-name: com.mysql.jdbc.Driver
data-username: root
data-password: 11111111
接下来我们再启动项目
默认启动为8080端口。接下来我们来访问一下项目:
在浏览器输入: http://127.0.0.1:8080/
结构如下:
因为springboot内部默认配置了一个tomcat ,所以我们可以直接访问,以前的tomat访问是一只猫的页面,现在不是了,如上图所示也是正确的。
三。编写controller
接下来我们来编写一个Controller类,写一个helloworld
package com.taoj.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@RequestMapping("/hello")
@ResponseBody
public String sayHello(){
return "hello world";
}
}
在类上我们添加 @Controller 注解 方法上添加 @RequestMapping() 和 @ResponseBody 注解
接下来我们重启一下项目。
启动没有报错,重新访问一下tomcat : http://127.0.0.1:8080/ 结果正常
接下来 访问http://127.0.0.1:8080/hello
页面为:
这就是一个最简单的springboot web项目
四。修改配置,
1.接下来我们来说一下,如何修改默认的tomcat端口,以及项目跟目录名
在配置文件 application.yml 文件中如下配置:
# 配置tomcat
server:
servlet:
context-path: /mybatis
port: 8085
完整的application.yml 如下:
# 配置数据源
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
driver-class-name: com.mysql.jdbc.Driver
data-username: root
data-password: 11111111
# 配置tomcat
server:
servlet:
context-path: /mybatis
port: 8085
重启项目后没有报错,继续访问:
http://127.0.0.1:8085/mybatis/hello
如上有没有发现,端口号和项目名已经变了
五。接下来我们说正事,要整合mybatis
先说一下,现在用的mybatis是配置文件的方式:
1.先新建一个数据库表
CREATE TABLE student(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20),
address VARCHAR(30)
);
SELECT * FROM student;
INSERT INTO student() VALUES (1001, '测试', '北京');
新建一个表,并插入一条语句
2.新建一个实体类Student
package com.taoj.entity;
public class Student {
private int id;
private String name;
private String address;
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 getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
}
3.添加一个Dao接口
package com.taoj.dao;
import com.taoj.entity.Student;
public interface StudentDao {
Student findOneStu(int id);
}
其中就只有一个方法 findOneStu(int id)
4.接下来添加一个Mapper文件
在resources文件夹下新建一个mapper文件夹,再创建一个StudentMapper.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.taoj.dao.StudentDao">
<select id="findOneStu" parameterType="int" resultType="com.taoj.entity.Student">
SELECT * FROM student WHERE id=#{id}
</select>
</mapper>
5.添加一个StudentService
代码如下:
package com.taoj.service;
import com.taoj.dao.StudentDao;
import com.taoj.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentService {
@Autowired
private StudentDao dao;
public Student findOneStu(int id){
return dao.findOneStu(id);
}
}
6.然后在application.yml文件中添加mybatis的映射文件路径:
# 指定mybatis映射文件地址:
mybatis:
mapper-locations: classpath:mapper/*.xml
application.yml完整文件如下:
# 配置数据源
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
driver-class-name: com.mysql.jdbc.Driver
data-username: root
data-password: 11111111
# 配置tomcat
server:
servlet:
context-path: /mybatis
port: 8085
# 指定mybatis映射文件地址:
mybatis:
mapper-locations: classpath:mapper/*.xml
7.接下来在Controller添加一个方法,
HelloController中完整代码如下:
package com.taoj.controller;
import com.taoj.entity.Student;
import com.taoj.service.StudentService;
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 HelloController {
@Autowired
private StudentService service;
@RequestMapping("/hello")
@ResponseBody
public String sayHello(){
return "hello world";
}
@RequestMapping("/find")
@ResponseBody
public String find(){
Student stu = new Student();
stu = service.findOneStu(1001);
return stu.toString();
}
}
8.接下来这一步非常重要:在启动类上添加对dao层的扫描,也就是在启动类上添加一个注解:
@MapperScan("com.taoj.dao")
启动类完整如下:
package com.taoj;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.taoj.dao")
public class SpringbootMybatis07Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatis07Application.class, args);
}
}
9.然后再启动项目,发现有个报错:
java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:965) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3978) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3914) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:871) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:4429) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1276) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2199) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2230) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2025) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:778) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_171]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_171]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_171]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_171]
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:386) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330) ~[mysql-connector-java-5.1.47.jar:5.1.47]
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:117) ~[HikariCP-2.7.9.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:365) ~[HikariCP-2.7.9.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:194) ~[HikariCP-2.7.9.jar:na]
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:460) [HikariCP-2.7.9.jar:na]
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:534) [HikariCP-2.7.9.jar:na]
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) [HikariCP-2.7.9.jar:na]
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) [HikariCP-2.7.9.jar:na]
at org.springframework.jdbc.datasource.DataSourceUtils.fetchConnection(DataSourceUtils.java:157) [spring-jdbc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:115) [spring-jdbc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:78) [spring-jdbc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
at org.mybatis.spring.transaction.SpringManagedTransaction.openConnection(SpringManagedTransaction.java:82) [mybatis-spring-2.0.0.jar:2.0.0]
at org.mybatis.spring.transaction.SpringManagedTransaction.getConnection(SpringManagedTransaction.java:68) [mybatis-spring-2.0.0.jar:2.0.0]
at org.apache.ibatis.executor.BaseExecutor.getConnection(BaseExecutor.java:336) [mybatis-3.5.0.jar:3.5.0]
at org.apache.ibatis.executor.SimpleExecutor.prepareStatement(SimpleExecutor.java:85) [mybatis-3.5.0.jar:3.5.0]
at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:62) [mybatis-3.5.0.jar:3.5.0]
at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:324) [mybatis-3.5.0.jar:3.5.0]
at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156) [mybatis-3.5.0.jar:3.5.0]
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109) [mybatis-3.5.0.jar:3.5.0]
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:83) [mybatis-3.5.0.jar:3.5.0]
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148) [mybatis-3.5.0.jar:3.5.0]
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141) [mybatis-3.5.0.jar:3.5.0]
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:77) [mybatis-3.5.0.jar:3.5.0]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_171]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_171]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_171]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_171]
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:433) [mybatis-spring-2.0.0.jar:2.0.0]
at com.sun.proxy.$Proxy57.selectOne(Unknown Source) [na:na]
at org.mybatis.spring.SqlSessionTemplate.selectOne(SqlSessionTemplate.java:166) [mybatis-spring-2.0.0.jar:2.0.0]
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:84) [mybatis-3.5.0.jar:3.5.0]
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:58) [mybatis-3.5.0.jar:3.5.0]
at com.sun.proxy.$Proxy58.findOneStu(Unknown Source) [na:na]
at com.taoj.service.StudentService.findOneStu(StudentService.java:15) [classes/:na]
at com.taoj.controller.HelloController.find(HelloController.java:26) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_171]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_171]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_171]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_171]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) [spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) [spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) [spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:891) [spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) [spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) [spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) [spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) [spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:981) [spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:873) [spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:858) [spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.5.37.jar:8.5.37]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) [spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) [spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) [spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498) [tomcat-embed-core-8.5.37.jar:8.5.37]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.37.jar:8.5.37]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_171]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_171]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.37.jar:8.5.37]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_171]
其中: java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO) 说明数据库连接不上,我们来看一看配置文件
把
data-username: root
data-password: 11111111
改为:
username: root
password: 11111111
然后再重新启动,报错消息,我们来访问一下:
http://127.0.0.1:8085/mybatis/hello
正常
访问: http://127.0.0.1:8085/mybatis/find
正常 ,搞定!!
以上为我学习springboot整合mybatis时记录的学习文章,供以后自己查看,也欢迎别人查看,我也是在前人的博客基础上自学的,现在感谢一下这些前辈:
https://blog.csdn.net/litianxiang_kaola/article/details/79481422
https://blog.csdn.net/saytime/article/details/74783296
https://blog.csdn.net/qq_35153200/article/details/79538434
不积跬步,无以至千里
不积小流,无以成江海
这里说一个插曲,我当时在调试这个demo的时候,总是有一个报错,NullPointException ,因为使用了mybatis后查询不到对象,toString()方法时报错了,我一直找不到原因,后来就重新来了一遍,居然成了。
最后附上完整代码地址: