当前位置: 首页 > article >正文

spring和Mybatis的逆向工程

在现代企业级开发中,使用Spring和MyBatis进行快速、高效的数据库操作是非常常见的。本文将深入探讨如何使用Spring和MyBatis进行逆向工程,帮助开发者自动生成数据库相关的代码,提高开发效率和代码质量。

一、什么是逆向工程

逆向工程是指从数据库表结构自动生成对应的Java实体类、Mapper接口和XML映射文件的过程。这种方法能够大大减少手动编写代码的时间,提高开发效率,减少人为错误。MyBatis提供了强大的逆向工程工具MyBatis Generator(MBG),结合Spring,可以实现快速开发。

二、Spring和MyBatis简介

1. Spring

Spring是一个开源的Java开发框架,提供全面的基础设施支持,包括依赖注入(DI)、面向切面编程(AOP)和数据访问框架。Spring与MyBatis的整合可以通过Spring提供的 SqlSessionFactoryBean和 MapperScannerConfigurer等类实现。

2. MyBatis

MyBatis是一个优秀的持久层框架,支持定制化SQL、存储过程以及高级映射。MyBatis相比Hibernate更加灵活和轻量级,特别适合复杂查询的应用场景。

三、逆向工程的准备工作

1. 环境配置

确保已经安装了以下环境:

  • JDK 1.8或以上版本
  • Maven 3.x
  • MySQL数据库(或其他数据库)
2. 项目依赖

在Maven项目的 pom.xml中添加以下依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.10</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.10</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.6</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.25</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-core</artifactId>
        <version>1.4.0</version>
    </dependency>
</dependencies>
​

四、MyBatis Generator配置

创建 generatorConfig.xml文件,用于配置MyBatis Generator:

<?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="MySqlContext" targetRuntime="MyBatis3">
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/your_database"
                        userId="your_username"
                        password="your_password"/>
        <javaModelGenerator targetPackage="com.example.model" targetProject="src/main/java"/>
        <sqlMapGenerator targetPackage="com.example.mapper" targetProject="src/main/resources"/>
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mapper" targetProject="src/main/java"/>
        <table tableName="your_table" domainObjectName="YourEntity"/>
    </context>
</generatorConfiguration>
​

五、运行MyBatis Generator

在Maven项目中运行MyBatis Generator命令:

mvn mybatis-generator:generate
​

这将根据 generatorConfig.xml配置文件生成对应的Java实体类、Mapper接口和XML映射文件。

六、Spring与MyBatis的整合

1. Spring配置文件

在 applicationContext.xml中配置Spring和MyBatis:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/your_database"/>
        <property name="username" value="your_username"/>
        <property name="password" value="your_password"/>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath*:com/example/mapper/*.xml"/>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.example.mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

</beans>
​

七、编写业务逻辑

1. 实体类

在 src/main/java/com/example/model/YourEntity.java中自动生成的实体类:

public class YourEntity {
    private Integer id;
    private String name;
    // getters and setters
}
​
2. Mapper接口

在 src/main/java/com/example/mapper/YourEntityMapper.java中自动生成的Mapper接口:

public interface YourEntityMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(YourEntity record);

    YourEntity selectByPrimaryKey(Integer id);

    int updateByPrimaryKey(YourEntity record);
}
​
3. XML映射文件

在 src/main/resources/com/example/mapper/YourEntityMapper.xml中自动生成的XML文件:

<mapper namespace="com.example.mapper.YourEntityMapper">
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
        DELETE FROM your_table WHERE id = #{id}
    </delete>
    <insert id="insert" parameterType="com.example.model.YourEntity">
        INSERT INTO your_table (name) VALUES (#{name})
    </insert>
    <select id="selectByPrimaryKey" resultType="com.example.model.YourEntity" parameterType="java.lang.Integer">
        SELECT id, name FROM your_table WHERE id = #{id}
    </select>
    <update id="updateByPrimaryKey" parameterType="com.example.model.YourEntity">
        UPDATE your_table SET name = #{name} WHERE id = #{id}
    </update>
</mapper>
​
4. 服务层

在 src/main/java/com/example/service/YourEntityService.java中编写服务层代码:

import com.example.mapper.YourEntityMapper;
import com.example.model.YourEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class YourEntityService {

    @Autowired
    private YourEntityMapper yourEntityMapper;

    public YourEntity getYourEntityById(Integer id) {
        return yourEntityMapper.selectByPrimaryKey(id);
    }

    public void saveYourEntity(YourEntity yourEntity) {
        if (yourEntity.getId() == null) {
            yourEntityMapper.insert(yourEntity);
        } else {
            yourEntityMapper.updateByPrimaryKey(yourEntity);
        }
    }

    public void deleteYourEntityById(Integer id) {
        yourEntityMapper.deleteByPrimaryKey(id);
    }
}
​

八、运行和测试

通过JUnit或Spring的测试框架测试逆向工程生成的代码,确保其能够正常工作


http://www.kler.cn/a/529255.html

相关文章:

  • Java小白入门教程:LinkedList
  • 安装anaconda3 后 电脑如何单独运行python,python还需要独立安装吗?
  • 数据密码解锁之DeepSeek 和其他 AI 大模型对比的神秘面纱
  • Python3 【闭包】项目实战:5个新颖的学习案例
  • 搜索引擎友好:设计快速收录的网站架构
  • 我的创作纪念日——成为创作者的 第365天(1年)
  • 在5G网络中使用IEEE 1588实现保持时间同步
  • 2025开源DouyinLiveRecorder全平台直播间录制工具整合包,多直播同时录制、教学直播录制、教学视频推送、简单易用不占内存
  • FLTK - FLTK1.4.1 - demo - bitmap
  • Redis脑裂问题详解及解决方案
  • 十分钟快速上手 markdown
  • DRM系列四:初始化drm设备--drm_dev_init
  • Linux+Docer 容器化部署之 Shell 语法入门篇 【Shell基本运算符】
  • 深度学习之“向量范数和距离度量”
  • 【VMware】VMware安装ubuntu-22.04虚拟机
  • 一觉醒来全球编码能力下降100000倍,新手小白的我决定科普C语言——函数
  • Clock Controller of RH850/F1KH-D8, RH850/F1KM-S4, RH850/F1KM-S2
  • 15JavaWeb——Maven高级篇
  • 深入剖析 HTML5 新特性:语义化标签和表单控件完全指南
  • 78-《磨盘草》
  • 代码随想录算法训练营第四十一天-动态规划-股票-123.买卖股票的最佳时机III
  • 帝国CMS8.0终极栏目转换或批量改顺序成功后不能返回地址的解决方案
  • Linux 基础2
  • Java线程池与Future_优化并发任务执行
  • DeepSeek-R1论文研读:通过强化学习激励LLM中的推理能力
  • Unity安装教学与相关问题