springboot整合mybatis使用代码生成器

springboot整合mybatis使用代码生成器

直接在项目中使用mybatis的代码生成器,生成的mapper接口、xml文件、pojo类位于指定的包内。相比较逆向工程的复制更方便,快速。

项目目录:
在这里插入图片描述

1.加依赖,配插件

创建一个springboot项目,使用的是在这里插入图片描述
快速构建项目。主要的依赖如下:

<dependencies>
   <!-- 
	======主要核心依赖=====
	-->
	<!--=====mybatis整合springboot依赖===-->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.2.2</version>
		</dependency>
		<!--mysql驱动-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.49</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<!--==========mybatis代码生成插件配置==========-->
			<plugin>
				<!--插件坐标-->
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.3.5</version>
				<!--插件依赖-->
				<dependencies>
					<dependency>
						<groupId>mysql</groupId>
						<artifactId>mysql-connector-java</artifactId>
						<version>5.1.49</version>
					</dependency>
				</dependencies>
				<!--插件配置-->
				<configuration>
                    <!--指定配置文件位置-->
					<configurationFile>generatorConfig.xml</configurationFile>
					<verbose>true</verbose>
					<overwrite>true</overwrite>
				</configuration>
			</plugin>
		</plugins>

web和test的springboot依赖,自己可以手动添加

2.配置

在pom文件中已经配置好了依赖和插件,只需要在项目的根目录创建一个generatorConfig.xml.内容和配置如下:

2.1 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>
	<context id="testTables" targetRuntime="MyBatis3">
		<commentGenerator>
			<!-- 是否去除自动生成的注释 true:是 : false:否 -->
			<property name="suppressAllComments" value="true" />
		</commentGenerator>
		<!--==================数据库连接的信息:驱动类、连接地址、用户名、密码 =====================-->
		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
			connectionURL="jdbc:mysql://localhost:3306/test" userId="root"
			password="root">
		</jdbcConnection>
		<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 
			NUMERIC 类型解析为java.math.BigDecimal -->
		<javaTypeResolver>
			<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>

		<!-- ================targetProject:生成PO类的位置 ================-->
		<javaModelGenerator targetPackage="com.bjsxt.pojo"
			targetProject=".\src\main\java">
			<!-- enableSubPackages:是否让schema作为包的后缀 -->
			<property name="enableSubPackages" value="false" />
			<!-- 从数据库返回的值被清理前后的空格 -->
			<property name="trimStrings" value="true" />
		</javaModelGenerator>
        <!--================= targetProject:mapper映射文件生成的位置=============== -->
		<sqlMapGenerator targetPackage="com.bjsxt.mapper"
			targetProject=".\src\main\java">
			<!-- enableSubPackages:是否让schema作为包的后缀 -->
			<property name="enableSubPackages" value="false" />
		</sqlMapGenerator>
		<!-- ==================targetPackage:mapper接口生成的位置 ==================-->
		<javaClientGenerator type="XMLMAPPER"
			targetPackage="com.bjsxt.mapper"
			targetProject=".\src\main\java">
			<!-- enableSubPackages:是否让schema作为包的后缀 -->
			<property name="enableSubPackages" value="false" />
		</javaClientGenerator>
		<!--=============== 指定数据库表 ==================-->
		<table schema="" tableName="user"></table>
	</context>
</generatorConfiguration>

2.2 页面报错解决:

该配置文件报错,添加相关约束即可。步骤如下:

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

约束文件mybatis-generator-config_1_0.dtd:

自己在桌面新建一个约束文件,添加以下内容,导入即可

<?xml version="1.0" encoding="UTF-8"?>
<!--

       Copyright 2006-2017 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->
<!--
  This DTD defines the structure of the MyBatis generator configuration file.
  Configuration files should declare the DOCTYPE as follows:
  
  <!DOCTYPE generatorConfiguration PUBLIC
    "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
    "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
  
  Please see the documentation included with MyBatis generator for details on each option
  in the DTD.  You may also view documentation on-line here:
  
  http://www.mybatis.org/generator/
  
-->

<!--
  The generatorConfiguration element is the root element for configurations.
-->
<!ELEMENT generatorConfiguration (properties?, classPathEntry*, context+)>
                        
<!--
  The properties element is used to define a standard Java properties file
  that contains placeholders for use in the remainder of the configuration
  file.
-->
<!ELEMENT properties EMPTY>
<!ATTLIST properties
  resource CDATA #IMPLIED
  url CDATA #IMPLIED>
  
<!--
  The context element is used to describe a context for generating files, and the source
  tables.
-->
<!ELEMENT context (property*, plugin*, commentGenerator?, (connectionFactory | jdbcConnection), javaTypeResolver?,
                         javaModelGenerator, sqlMapGenerator?, javaClientGenerator?, table+)>
<!ATTLIST context id ID #REQUIRED
  defaultModelType CDATA #IMPLIED
  targetRuntime CDATA #IMPLIED
  introspectedColumnImpl CDATA #IMPLIED>

<!--
  The connectionFactory element is used to describe the connection factory used
  for connecting to the database for introspection.  Either connectionFacoty
  or jdbcConnection must be specified, but not both.
-->
<!ELEMENT connectionFactory (property*)>
<!ATTLIST connectionFactory
  type CDATA #IMPLIED>

<!--
  The jdbcConnection element is used to describe the JDBC connection that the generator
  will use to introspect the database.
-->
<!ELEMENT jdbcConnection (property*)>
<!ATTLIST jdbcConnection 
  driverClass CDATA #REQUIRED
  connectionURL CDATA #REQUIRED
  userId CDATA #IMPLIED
  password CDATA #IMPLIED>

<!--
  The classPathEntry element is used to add the JDBC driver to the run-time classpath.
  Repeat this element as often as needed to add elements to the classpath.
-->
<!ELEMENT classPathEntry EMPTY>
<!ATTLIST classPathEntry
  location CDATA #REQUIRED>

<!--
  The property element is used to add custom properties to many of the generator's
  configuration elements.  See each element for example properties.
  Repeat this element as often as needed to add as many properties as necessary
  to the configuration element.
-->
<!ELEMENT property EMPTY>
<!ATTLIST property
  name CDATA #REQUIRED
  value CDATA #REQUIRED>

<!--
  The plugin element is used to define a plugin.
-->
<!ELEMENT plugin (property*)>
<!ATTLIST plugin
  type CDATA #REQUIRED>

<!--
  The javaModelGenerator element is used to define properties of the Java Model Generator.
  The Java Model Generator builds primary key classes, record classes, and Query by Example 
  indicator classes.
-->
<!ELEMENT javaModelGenerator (property*)>
<!ATTLIST javaModelGenerator
  targetPackage CDATA #REQUIRED
  targetProject CDATA #REQUIRED>

<!--
  The javaTypeResolver element is used to define properties of the Java Type Resolver.
  The Java Type Resolver is used to calculate Java types from database column information.
  The default Java Type Resolver attempts to make JDBC DECIMAL and NUMERIC types easier
  to use by substituting Integral types if possible (Long, Integer, Short, etc.)
-->
<!ELEMENT javaTypeResolver (property*)>
<!ATTLIST javaTypeResolver
  type CDATA #IMPLIED>

<!--
  The sqlMapGenerator element is used to define properties of the SQL Map Generator.
  The SQL Map Generator builds an XML file for each table that conforms to iBATIS'
  SqlMap DTD.
-->
<!ELEMENT sqlMapGenerator (property*)>
<!ATTLIST sqlMapGenerator
  targetPackage CDATA #REQUIRED
  targetProject CDATA #REQUIRED>

<!--
  The javaClientGenerator element is used to define properties of the Java client Generator.
  The Java Client Generator builds Java interface and implementation classes
  (as required) for each table.
  If this element is missing, then the generator will not build Java Client classes.
-->
<!ELEMENT javaClientGenerator (property*)>
<!ATTLIST javaClientGenerator
  type CDATA #REQUIRED
  targetPackage CDATA #REQUIRED
  targetProject CDATA #REQUIRED
  implementationPackage CDATA #IMPLIED>

<!--
  The table element is used to specify a database table that will be the source information
  for a set of generated objects.
-->
<!ELEMENT table (property*, generatedKey?, domainObjectRenamingRule?, columnRenamingRule?, (columnOverride | ignoreColumn | ignoreColumnsByRegex)*) >
<!ATTLIST table
  catalog CDATA #IMPLIED
  schema CDATA #IMPLIED
  tableName CDATA #REQUIRED
  alias CDATA #IMPLIED
  domainObjectName CDATA #IMPLIED
  mapperName CDATA #IMPLIED
  sqlProviderName CDATA #IMPLIED
  enableInsert CDATA #IMPLIED
  enableSelectByPrimaryKey CDATA #IMPLIED
  enableSelectByExample CDATA #IMPLIED
  enableUpdateByPrimaryKey CDATA #IMPLIED
  enableDeleteByPrimaryKey CDATA #IMPLIED
  enableDeleteByExample CDATA #IMPLIED
  enableCountByExample CDATA #IMPLIED
  enableUpdateByExample CDATA #IMPLIED
  selectByPrimaryKeyQueryId CDATA #IMPLIED
  selectByExampleQueryId CDATA #IMPLIED
  modelType CDATA #IMPLIED
  escapeWildcards CDATA #IMPLIED
  delimitIdentifiers CDATA #IMPLIED
  delimitAllColumns CDATA #IMPLIED>

<!--
  The columnOverride element is used to change certain attributes of the column
  from their default values.
-->
<!ELEMENT columnOverride (property*)>
<!ATTLIST columnOverride
  column CDATA #REQUIRED
  property CDATA #IMPLIED
  javaType CDATA #IMPLIED
  jdbcType CDATA #IMPLIED
  typeHandler CDATA #IMPLIED
  isGeneratedAlways CDATA #IMPLIED
  delimitedColumnName CDATA #IMPLIED>

<!--
  The ignoreColumn element is used to identify a column that should be ignored.
  No generated SQL will refer to the column, and no property will be generated
  for the column in the model objects.
-->
<!ELEMENT ignoreColumn EMPTY>
<!ATTLIST ignoreColumn
  column CDATA #REQUIRED
  delimitedColumnName CDATA #IMPLIED>

<!--
  The ignoreColumnsByRegex element is used to identify a column pattern that should be ignored.
  No generated SQL will refer to the column, and no property will be generated
  for the column in the model objects.
-->
<!ELEMENT ignoreColumnsByRegex (except*)>
<!ATTLIST ignoreColumnsByRegex
  pattern CDATA #REQUIRED>

<!--
  The except element is used to identify an exception to the ignoreColumnsByRegex rule.
  If a column matches the regex rule, but also matches the exception, then the
  column will be included in the generated objects.
-->
<!ELEMENT except EMPTY>
<!ATTLIST except
  column CDATA #REQUIRED
  delimitedColumnName CDATA #IMPLIED>

<!--
  The generatedKey element is used to identify a column in the table whose value
  is calculated - either from a sequence (or some other query), or as an identity column.
-->
<!ELEMENT generatedKey EMPTY>
<!ATTLIST generatedKey
  column CDATA #REQUIRED
  sqlStatement CDATA #REQUIRED
  identity CDATA #IMPLIED
  type CDATA #IMPLIED>

<!--
  The domainObjectRenamingRule element is used to specify a rule for renaming
  object domain name before the corresponding domain object name is calculated
-->
<!ELEMENT domainObjectRenamingRule EMPTY>
<!ATTLIST domainObjectRenamingRule
  searchString CDATA #REQUIRED
  replaceString CDATA #IMPLIED>

<!--
  The columnRenamingRule element is used to specify a rule for renaming
  columns before the corresponding property name is calculated
-->
<!ELEMENT columnRenamingRule EMPTY>
<!ATTLIST columnRenamingRule
  searchString CDATA #REQUIRED
  replaceString CDATA #IMPLIED>

<!--
  The commentGenerator element is used to define properties of the Comment Generator.
  The Comment Generator adds comments to generated elements.
-->
<!ELEMENT commentGenerator (property*)>
<!ATTLIST commentGenerator
  type CDATA #IMPLIED>
  

3.运行插件

在这里插入图片描述

4.结果

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot是一种用于快速构建 Spring 应用程序的框架。而 MyBatis 是一个持久层框架,可以让你简化数据库操作。 在 Spring Boot整合 MyBatis 有几种方式,下面给出其中一种基本的方式: 1. 在 pom.xml 文件中添加 MyBatis 依赖: ``` <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency> ``` 2. 创建数据库配置文件 application.properties,在其中配置数据库连接信息。 3. 在启动类上添加 @MapperScan 注解,用于扫描 MyBatis 的接口。例如: ``` @MapperScan("com.example.demo.mapper") ``` 4. 创建 MyBatis 接口,并使用 @Mapper 注解标注。例如: ``` @Mapper public interface UserMapper { // ... } ``` 这样就完成了 Spring BootMyBatis整合,您就可以在项目中使用 MyBatis 操作数据库了。 如需进一步深入,我建议您查看官方文档以获得更详细的信息。 ### 回答2: Spring Boot是一个开源的Java开发框架,可以方便地创建独立的、基于Spring的应用程序。MyBatis是一个优秀的持久层框架,可以用来简化数据库访问操作。 Spring Boot整合MyBatis的步骤如下: 1. 在pom.xml文件中,添加MyBatis和数据库驱动的依赖。可以通过Maven或Gradle等构建工具来管理依赖。 2. 在application.properties或application.yml中配置数据库相关的信息,例如数据库连接URL、用户名、密码等。 3. 创建一个数据源(DataSource)的Bean,用于连接数据库。可以使用Spring Boot提供的默认数据源或者自定义数据源。 4. 创建一个SqlSessionFactoryBean的Bean,用于配置MyBatis的核心配置文件(mybatis-config.xml)和映射文件(mapper.xml)的路径。 5. 创建一个MapperScannerConfigurer的Bean,用于扫描并注册Mapper接口。 6. 创建Mapper接口,并使用@Mapper注解标记该接口。在接口方法中定义SQL语句和参数映射的方法。 7. 在业务逻辑中,使用@Autowired注解注入Mapper接口的实例。即可通过Mapper接口的方法来访问数据库。 整合完成后,我们可以使用MyBatis提供的注解或XML配置来编写SQL语句,然后通过调用Mapper接口的方法来执行SQL查询和更新操作。同时,通过Spring Boot的自动配置特性,我们不需要像传统的Web应用一样手动配置数据库连接池和事务管理器等组件,可以更加简化和集中化配置。 通过Spring Boot整合MyBatis,我们可以更加方便地使用MyBatis来访问数据库,同时充分利用Spring Boot的优势,如自动配置、热部署、健康检查等。这样可以大大提高开发效率,减少代码量,并且更容易维护和扩展。 ### 回答3: Spring Boot是一个用于快速开发和部署的开源框架,而MyBatis是一个持久层框架,用于与关系型数据库进行交互。将它们两个整合在一起可以提高开发效率并简化代码。 要实现Spring Boot整合MyBatis,首先需要在pom.xml文件中添加相应的依赖。这些依赖包括spring-boot-starter-web、spring-boot-starter-data-jpa以及mybatis-spring-boot-starter等。 其次,需要在配置文件中配置数据源和MyBatis相关的配置。可以将相关配置放在application.properties或者application.yml文件中。在配置数据源时,需要指定数据库的连接信息。 然后,创建一个数据访问对象(DAO)接口,并使用MyBatis的注解或XML文件定义数据访问的方法。这些方法可以使用MyBatis提供的一些注解来定义SQL语句,或者使用XML文件来进行映射。 接下来,在Service层中使用@Autowired注解将DAO接口注入,然后在Service中调用DAO的方法完成数据操作。 最后,创建一个Spring Boot的启动类,在该类中使用@SpringBootApplication注解启动Spring Boot应用。 整合完成后,就可以通过访问Controller来调用Service层的方法,实现与数据库的交互。 Spring Boot整合MyBatis还可以通过配置文件自动生成数据库表结构和实体类,简化开发过程。 总的来说,Spring Boot整合MyBatis能够帮助开发者快速搭建数据库访问层,并提供了简洁、高效的开发方式。通过这样的整合,可以更加轻松地进行数据库操作,提高开发效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值