• 搭建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.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>
      </dependencies>
      <build>
        <plugins>
          <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
          </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.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.1</version>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.15</version>
            </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.generator</groupId>
                    <artifactId>mybatis-generator-maven-plugin</artifactId>
                    <version>1.3.2</version>
                    <configuration>
                        <configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile>
                        <overwrite>false</overwrite>
                        <verbose>true</verbose>
                    </configuration>
                    <dependencies>
                        <dependency>
                            <groupId>mysql</groupId>
                            <artifactId>mysql-connector-java</artifactId>
                            <!--<version>5.1.39</version>-->
                            <version>8.0.17</version>
                        </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>
            <!--生成Dao类存放位置-->
            <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>
            <!--生成Model类存放位置-->
            <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.<init>(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对象的属性名,而不是表格的字段名。
    <insert id="insert" parameterType="Spares"
    useGeneratedKeys="true" keyProperty="id">
    insert into system(name) values(#{name})
    </insert>
    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

  • 相关阅读:
    es6+最佳入门实践(11)
    es6+最佳入门实践(10)
    es6+最佳入门实践(9)
    es6+最佳入门实践(8)
    es6+最佳入门实践(7)
    cookie、session、sessionid 与jsessionid之间的关系
    百面数据挖掘工程师-题库(1)
    远程桌面最新漏洞CVE-2019-0708 POC利用复现
    jQuery基础
    JavaScript 基础
  • 原文地址:https://www.cnblogs.com/afraidToForget/p/12080801.html
Copyright © 2020-2023  润新知