搭建Spring MyBatis MySQL后台服务

 

spring官方推荐的项目配置参考页面: https://start.spring.io/ 

 

背景介绍:常见Web服务器都会使用Spring Boot框架,Spring是一个广泛应用的Http服务器。

本文介绍如何搭建Spring、MyBatist、MySQL的后台服务,以及相关问题。

 

1、配置Spring Web项目

在pom.xml中配置如下依赖:

<dependencies>
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-webartifactId>
    dependency>
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-testartifactId>
      <scope>testscope>
      <exclusions>
        <exclusion>
          <groupId>org.junit.vintagegroupId>
          <artifactId>junit-vintage-engineartifactId>
        exclusion>
      exclusions>
    dependency>
  dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-maven-pluginartifactId>
      plugin>
    plugins>
  build>
View Code

添加Spring启动类:(这个类的包层级要比其他java类文件的包层级都要高。)

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}
View Code

在application.properties中配置服务占用的端口:

server.port=8080

 

2、配置mybatis和MySQL

在pom.xml中配置以下依赖:

 <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.1.1version>
        dependency>

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.15version>
        dependency>
View Code

在application.properties配置文件中添加下面的配置

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/teach_cn
spring.datasource.username=root
spring.datasource.password=12345678
mybatis.config-location=classpath:mybatis/mybatis.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
View Code

在spring启动类上配置mapper扫描注解:

@SpringBootApplication
@MapperScan(basePackages = "com.test")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}
View Code

MySQL 6 以后的版本中com.mysql.jdbc.Driver被com.mysql.cj.jdbc.Driver所替代,不需要显示配置,原因如下

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

即不用写下面的内容:

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

 

 

2、在MySQL中创建好数据表之后,自动生成Mybatis的Mapper.xml文件、Java的实体类文件和mapper接口。

首先,在项目的pom.xml中添加mybatis-generator插件:

 <plugin>
                <groupId>org.mybatis.generatorgroupId>
                <artifactId>mybatis-generator-maven-pluginartifactId>
                <version>1.3.2version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generatorConfig.xmlconfigurationFile>
                    <overwrite>falseoverwrite>
                    <verbose>trueverbose>
                configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysqlgroupId>
                        <artifactId>mysql-connector-javaartifactId>
                        
                        <version>8.0.17version>
                    dependency>
                dependencies>
            plugin>
View Code

其中,generatorConfig.xml内容如下:

xml version="1.0" encoding="UTF-8"?>
DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    
    <classPathEntry
            location="/Users/kyh/.m2/repository/mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar"/>
    <context id="context" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        commentGenerator>
        
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/teach_cn?serverTimezone=UTC" userId="root"
                        password="12345678">
        jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        javaTypeResolver>
        
        <javaModelGenerator targetPackage="com.teach.cloud.note.mysql.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        javaModelGenerator>
        
        <sqlMapGenerator targetPackage="mybatis.mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        sqlMapGenerator>
        
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.teach.cloud.note.mysql.mapper"
                             targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        javaClientGenerator>

        
        <table tableName="id_config" domainObjectName="IdConfig" enableCountByExample="false"
               enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">table>
        <table tableName="user_password" domainObjectName="userpasswordDAO" enableCountByExample="false"
               enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">table>
    context>
generatorConfiguration>
View Code

运行该插件:

在Terminal窗口执行命令 mvn mybatis-generator:generate  

或者在idea的maven窗口中双击对应的插件目标执行。

 

常见问题介绍和解决:

1、 mapper.xml 文件没有打进jar包引起的错误。

问题: 

org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.teach.cloud.note.mysql.mapper.IdConfigMapper.insert
at org.apache.ibatis.binding.MapperMethod$SqlCommand.(MapperMethod.java:235) ~[mybatis-3.5.3.jar:3.5.3]
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:

解决:  

在application.properties配置文件中添加下面的配置,和mybatis.xml 的内容


mybatis.config-location=classpath:mybatis/mybatis.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

mybatis.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>
    <typeAliases>
        <typeAlias alias="Integer" type="java.lang.Integer"/>
        <typeAlias alias="Long" type="java.lang.Long"/>
        <typeAlias alias="HashMap" type="java.util.HashMap"/>
        <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap"/>
        <typeAlias alias="ArrayList" type="java.util.ArrayList"/>
        <typeAlias alias="LinkedList" type="java.util.LinkedList"/>
    typeAliases>
configuration>
View Code

 

2、

配置Spring打印日志的级别:

在application.properties中配置:(可以使用root级别和package级别来控制日志的输入级别)

logging.level.root= WARN
logging.level.org.springframework.security= DEBUG
logging.level.org.springframework.web= ERROR
logging.level.org.hibernate= DEBUG
logging.level.org.apache.commons.dbcp2= DEBUG

 

3、

问题:

使用mybatis插入数据的时候,获取插入记录的主键信息:

解决:

在Mybatis Mapper文件中添加属性“useGeneratedKeys”和“keyProperty”,其中keyProperty是Java对象的属性名,而不是表格的字段名。
useGeneratedKeys="true" keyProperty="id">
insert into system(name) values(#{name})

Mybatis执行完插入语句后,自动将自增长值赋值给对象systemBean的属性id。因此,可通过systemBean对应的getter方法获取!
int count = systemService.insert(systemBean);
int id = systemBean.getId(); //获取到的即为新插入记录的ID

 

4、

类unix系统如何登陆mysql

命令如下,其中-P3306是端口: mysql -uroot -p -P3306 -h127.0.0.1

你可能感兴趣的:(搭建Spring MyBatis MySQL后台服务)