SpringBoot2.x入门:使用MyBatis

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS PostgreSQL,高可用系列 2核4GB
云数据库 RDS MySQL,高可用系列 2核4GB
简介: 这篇文章是《SpringBoot2.x入门》专辑的「第8篇」文章,使用的SpringBoot版本为2.3.1.RELEASE,JDK版本为1.8。

网络异常,图片无法展示
|


这是公众号《Throwable文摘》发布的第25篇原创文章,收录于专辑《SpringBoot2.x入门》。


前提



这篇文章是《SpringBoot2.x入门》专辑的第8篇文章,使用的SpringBoot版本为2.3.1.RELEASEJDK版本为1.8


SpringBoot项目引入MyBatis一般的套路是直接引入mybatis-spring-boot-starter或者使用基于MyBatis进行二次封装的框架例如MyBatis-Plus或者tk.mapper等,但是本文会使用一种更加原始的方式,单纯依赖org.mybatis:mybatisorg.mybatis:mybatis-springMyBatis的功能整合到SpringBoot中,Spring(Boot)使用的是微内核架构,任何第三方框架或者插件都可以按照本文的思路融合到该微内核中。


引入MyBatis依赖



编写本文的时候(2020-07-18org.mybatis:mybatis的最新版本是3.5.5,而org.mybatis:mybatis-spring的最新版本是2.0.5,在使用BOM管理SpringBoot版本的前提下,引入下面的依赖:


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.5</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.5</version>
</dependency>
复制代码


注意的是低版本的MyBatis如果需要使用JDK8的日期时间API,需要额外引入mybatis-typehandlers-jsr310依赖,但是某个版本之后mybatis-typehandlers-jsr310中的类已经移植到org.mybatis:mybatis中作为内建类,可以放心使用JDK8的日期时间API。


添加MyBatis配置



MyBatis的核心模块是SqlSessionFactoryMapperScannerConfigurer。前者可以使用SqlSessionFactoryBean,功能是为每个SQL的执行提供SqlSession和加载全局配置或者SQL实现的XML文件,后者是一个BeanDefinitionRegistryPostProcessor实现,主要功能是主动通过配置的基础包(Base Package)中递归搜索Mapper接口(这个算是MyBatis独有的扫描阶段,务必指定明确的扫描包,否则会因为效率太低导致启动阶段耗时增加),并且把它们注册成MapperFactoryBean(简单理解为接口动态代理实现添加到方法缓存中,并且委托到IOC容器,此后可以直接注入Mapper接口),注意这个BeanFactoryPostProcessor的回调优先级极高,在自动装配@Autowired族注解或者@ConfigurationProperties属性绑定处理之前已经回调,因此在处理MapperScannerConfigurer的属性配置时候绝对不能使用@Value或者自定义前缀属性Bean进行自动装配,但是可以从Environment中直接获取。


这里添加一个自定义属性前缀mybatis,用于绑定配置文件中的属性到MyBatisProperties类中:


@ConfigurationProperties(prefix = "mybatis")
@Data
public class MyBatisProperties {
    private String configLocation;
    private String mapperLocations;
    private String mapperPackages;
    private static final ResourcePatternResolver RESOLVER = new PathMatchingResourcePatternResolver();
    /**
     * 转化Mapper映射文件为Resource
     */
    public Resource[] getMapperResourceArray() {
        if (!StringUtils.hasLength(mapperLocations)) {
            return new Resource[0];
        }
        List<Resource> resources = new ArrayList<>();
        String[] locations = StringUtils.commaDelimitedListToStringArray(mapperLocations);
        for (String location : locations) {
            try {
                resources.addAll(Arrays.asList(RESOLVER.getResources(location)));
            } catch (IOException e) {
                throw new IllegalArgumentException(e);
            }
        }
        return resources.toArray(new Resource[0]);
    }
}
复制代码


接着添加一个MybatisAutoConfiguration用于配置SqlSessionFactory


@Configuration
@EnableConfigurationProperties(value = {MyBatisProperties.class})
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
@RequiredArgsConstructor
public class MybatisAutoConfiguration {
    private final MyBatisProperties myBatisProperties;
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        // 其实核心配置就是这两项,其他TypeHandlersPackage、TypeAliasesPackage等等自行斟酌是否需要添加
        bean.setConfigLocation(new ClassPathResource(myBatisProperties.getConfigLocation()));
        bean.setMapperLocations(myBatisProperties.getMapperResourceArray());
        return bean;
    }
    /**
     * 事务模板,用于编程式事务 - 可选配置
     */
    @Bean
    @ConditionalOnMissingBean
    public TransactionTemplate transactionTemplate(PlatformTransactionManager platformTransactionManager) {
        return new TransactionTemplate(platformTransactionManager);
    }
    /**
     * 数据源事务管理器 - 可选配置
     */
    @Bean
    @ConditionalOnMissingBean
    public PlatformTransactionManager platformTransactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
复制代码


一般情况下,启用事务需要定义PlatformTransactionManager的实现,而TransactionTemplate适用于编程式事务(和声明式事务@Transactional区别,编程式更加灵活)。上面的配置类中只使用了两个属性,而mybatis.mapperPackages将用于MapperScannerConfigurer的加载上。添加MapperScannerRegistrarConfiguration如下:


@Configuration
public class MapperScannerRegistrarConfiguration {
    public static class AutoConfiguredMapperScannerRegistrar implements
            BeanFactoryAware, EnvironmentAware, ImportBeanDefinitionRegistrar {
        private Environment environment;
        private BeanFactory beanFactory;
        @Override
        public void setBeanFactory(@NonNull BeanFactory beanFactory) throws BeansException {
            this.beanFactory = beanFactory;
        }
        @Override
        public void setEnvironment(@NonNull Environment environment) {
            this.environment = environment;
        }
        @Override
        public void registerBeanDefinitions(@NonNull AnnotationMetadata importingClassMetadata,
                                            @NonNull BeanDefinitionRegistry registry) {
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class);
            builder.addPropertyValue("processPropertyPlaceHolders", true);
            StringJoiner joiner = new StringJoiner(ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
            // 这里使用了${mybatis.mapperPackages},否则会使用AutoConfigurationPackages.get(this.beanFactory)获取项目中自定义配置的包
            String mapperPackages = environment.getProperty("mybatis.mapperPackages");
            if (null != mapperPackages) {
                String[] stringArray = StringUtils.commaDelimitedListToStringArray(mapperPackages);
                for (String pkg : stringArray) {
                    joiner.add(pkg);
                }
            } else {
                List<String> packages = AutoConfigurationPackages.get(this.beanFactory);
                for (String pkg : packages) {
                    joiner.add(pkg);
                }
            }
            builder.addPropertyValue("basePackage", joiner.toString());
            BeanWrapper beanWrapper = new BeanWrapperImpl(MapperScannerConfigurer.class);
            Stream.of(beanWrapper.getPropertyDescriptors())
                    .filter(x -> "lazyInitialization".equals(x.getName())).findAny()
                    .ifPresent(x -> builder.addPropertyValue("lazyInitialization",
                            "${mybatis.lazyInitialization:false}"));
            registry.registerBeanDefinition(MapperScannerConfigurer.class.getName(), builder.getBeanDefinition());
        }
    }
    @Configuration
    @Import(AutoConfiguredMapperScannerRegistrar.class)
    @ConditionalOnMissingBean({MapperFactoryBean.class, MapperScannerConfigurer.class})
    public static class MapperScannerRegistrarNotFoundConfiguration {
    }
}
复制代码


到此基本的配置Bean已经定义完毕,接着需要添加配置项。一般一个项目的MyBatis配置是相对固定的,可以直接添加在主配置文件application.properties中:


server.port=9098
spring.application.name=ch8-mybatis
mybatis.configLocation=mybatis-config.xml
mybatis.mapperLocations=classpath:mappings/base,classpath:mappings/ext
mybatis.mapperPackages=club.throwable.ch8.repository.mapper,club.throwable.ch8.repository
复制代码


个人喜欢在resource/mappings目录下定义baseext两个目录,base目录用于存在MyBatis生成器生成的XML文件,这样就能在后续添加了表字段之后直接重新生成和覆盖base目录下对应的XML文件即可。同理,在项目的源码包下建repository/mapper,然后Mapper类直接存放在repository/mapper目录,DAO类存放在repository目录,MyBatis生成器生成的Mapper类可以直接覆盖repository/mapper目录中对应的类。


resources目录下添加一个MyBatis的全局配置文件mybatis-config.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>
    <settings>
        <!--下划线转驼峰-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--未知列映射忽略-->
        <setting name="autoMappingUnknownColumnBehavior" value="NONE"/>
    </settings>
</configuration>
复制代码


项目目前的基本结构如下:


微信截图_20220513155554.png


使用Mybatis



为了简单起见,这里使用h2内存数据库进行演示。添加h2的依赖:


<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.200</version>
</dependency>
复制代码


resources目录下添加一个schema.sqldata.sql


// resources/schema.sql
drop table if exists customer;
create table customer
(
    id            bigint generated by default as identity,
    customer_name varchar(32),
    age           int,
    create_time   timestamp default current_timestamp,
    edit_time     timestamp default current_timestamp,
    primary key (id)
);
// resources/data.sql
INSERT INTO customer(customer_name,age) VALUES ('doge', 22);
INSERT INTO customer(customer_name,age) VALUES ('throwable', 23);
复制代码


添加对应的实体类club.throwable.ch8.entity.Customer


@Data
public class Customer {
    private Long id;
    private String customerName;
    private Integer age;
    private LocalDateTime createTime;
    private LocalDateTime editTime;
}
复制代码


添加MapperDAO类:


// club.throwable.ch8.repository.mapper.CustomerMapper
public interface CustomerMapper {
}
// club.throwable.ch8.repository.CustomerDao
public interface CustomerDao extends CustomerMapper {
    Customer queryByName(@Param("customerName") String customerName);
}
复制代码


添加XML文件resource/mappings/base/BaseCustomerMapper.xmlresource/mappings/base/ExtCustomerMapper.xml


// BaseCustomerMapper.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="club.throwable.ch8.repository.mapper.CustomerMapper">
    <resultMap id="BaseResultMap" type="club.throwable.ch8.entity.Customer">
        <id column="id" jdbcType="BIGINT" property="id"/>
        <result column="customer_name" jdbcType="VARCHAR" property="customerName"/>
        <result column="age" jdbcType="INTEGER" property="age"/>
        <result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
        <result column="edit_time" jdbcType="TIMESTAMP" property="editTime"/>
    </resultMap>
</mapper>
// ExtCustomerMapper.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="club.throwable.ch8.repository.CustomerDao">
    <resultMap id="BaseResultMap" type="club.throwable.ch8.entity.Customer"
               extends="club.throwable.ch8.repository.mapper.CustomerMapper.BaseResultMap">
    </resultMap>
    <select id="queryByName" resultMap="BaseResultMap">
        SELECT *
        FROM customer
        WHERE customer_name = #{customerName}
    </select>
</mapper>
复制代码


细心的伙伴会发现,DAO和Mapper类是继承关系,而ext和base下对应的Mapper文件中的BaseResultMap也是继承关系


配置文件中增加h2数据源的配置:


// application.properties
spring.datasource.url=jdbc:h2:mem:db_customer;MODE=MYSQL;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=FALSE
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=org.h2.Driver
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.h2.console.settings.web-allow-others=true
spring.datasource.schema=classpath:schema.sql
spring.datasource.data=classpath:data.sql
复制代码


添加一个启动类进行验证:


public class Ch8Application implements CommandLineRunner {
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private ObjectMapper objectMapper;
    public static void main(String[] args) {
        SpringApplication.run(Ch8Application.class, args);
    }
    @Override
    public void run(String... args) throws Exception {
        Customer customer = customerDao.queryByName("doge");
        log.info("Query [name=doge],result:{}", objectMapper.writeValueAsString(customer));
        customer = customerDao.queryByName("throwable");
        log.info("Query [name=throwable],result:{}", objectMapper.writeValueAsString(customer));
    }
}
复制代码


执行结果如下:


微信截图_20220513155603.png


使用Mybatis生成器生成Mapper文件



有些时候为了提高开发效率,更倾向于使用生成器去预生成一些已经具备简单CRUD方法的Mapper文件,这个时候可以使用mybatis-generator-core。编写本文的时候(2020-07-18mybatis-generator-core的最新版本为1.4.0mybatis-generator-core可以通过编程式使用或者Maven插件形式使用。


这里仅仅简单演示一下Maven插件形式下使用mybatis-generator-core的方式,关于mybatis-generator-core后面会有一篇数万字的文章详细介绍此生成器的使用方式和配置项的细节。在项目的resources目录下添加一个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="H2Tables" targetRuntime="MyBatis3">
        <property name="autoDelimitKeywords" value="true"/>
        <property name="javaFileEncoding" value="UTF-8"/>
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
        </commentGenerator>
        <jdbcConnection driverClass="org.h2.Driver"
                        connectionURL="jdbc:h2:mem:db_customer;MODE=MYSQL;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=FALSE"
                        userId="root"
                        password="123456"/>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成模型的包名和位置(实体类)-->
        <javaModelGenerator targetPackage="club.throwable.ch8.entity"
                            targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="false"/>
        </javaModelGenerator>
        <!-- 生成映射XML文件的包名和位置-->
        <sqlMapGenerator targetPackage="mappings.base"
                         targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置-->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="club.throwable.ch8.repository.mapper"
                             targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <table tableName="customer"
               enableCountByExample="false"
               enableUpdateByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false">
        </table>
    </context>
</generatorConfiguration>
复制代码


然后再项目的POM文件添加一个Maven插件:


<plugins>
    <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.4.0</version>
        <executions>
            <execution>
                <id>Generate MyBatis Artifacts</id>
                <goals>
                    <goal>generate</goal>
                </goals>
            </execution>
        </executions>
        <configuration>
            <jdbcURL>jdbc:h2:mem:db_customer;MODE=MYSQL;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=FALSE</jdbcURL>
            <jdbcDriver>org.h2.Driver</jdbcDriver>
            <jdbcUserId>root</jdbcUserId>
            <jdbcPassword>123456</jdbcPassword>
            <sqlScript>${basedir}/src/main/resources/schema.sql</sqlScript>
        </configuration>
        <dependencies>
            <dependency>
                <groupId>com.h2database</groupId>
                <artifactId>h2</artifactId>
                <version>1.4.200</version>
            </dependency>
        </dependencies>
    </plugin>
</plugins>
复制代码


笔者发现这里必须要在插件的配置中重新定义数据库连接属性和schema.sql,因为插件跑的时候无法使用项目中已经启动的h2实例,具体原因未知。


配置完毕之后,执行Maven命令:


mvn -Dmybatis.generator.overwrite=true mybatis-generator:generate -X
复制代码


微信截图_20220513155615.png


然后resource/mappings/base目录下新增了一个带有基本CRUD方法实现的CustomerMapper.xml,同时CustoemrMapper接口和Customer实体也被重新覆盖生成了。


微信截图_20220513155622.png


这里把前面手动编写的BaseCustomerMapper.xml注释掉,预防冲突。另外,CustomerMapper.xml的insertSelective标签需要加上keyColumn="id" keyProperty="id" useGeneratedKeys="true"属性,用于实体insert后的主键回写。


最后,修改并重启启动一下Ch8Application验证结果:


微信截图_20220513155629.png


小结



这篇文章相对详细地介绍了SpringBoot项目如何使用MyBatis,如果需要连接MySQL或者其他数据库,只需要修改数据源配置和MyBatis生成器的配置文件即可,其他配置类和项目骨架可以直接复用。


本文demo仓库:


(本文完 c-2-d e-a-20200719 封面来自《秒速五厘米》)

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
6月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
299 0
|
3月前
|
Java 数据库连接 数据库
Spring boot 使用mybatis generator 自动生成代码插件
本文介绍了在Spring Boot项目中使用MyBatis Generator插件自动生成代码的详细步骤。首先创建一个新的Spring Boot项目,接着引入MyBatis Generator插件并配置`pom.xml`文件。然后删除默认的`application.properties`文件,创建`application.yml`进行相关配置,如设置Mapper路径和实体类包名。重点在于配置`generatorConfig.xml`文件,包括数据库驱动、连接信息、生成模型、映射文件及DAO的包名和位置。最后通过IDE配置运行插件生成代码,并在主类添加`@MapperScan`注解完成整合
610 1
Spring boot 使用mybatis generator 自动生成代码插件
|
8月前
|
SQL 缓存 Java
【吐血整理】MyBatis从入门到精通
本文介绍了 MyBatis 的使用指南,涵盖开发环境搭建、基础操作实例和进阶特性。首先,详细描述了 JDK 和 IDE 的安装及依赖引入,确保项目顺利运行。接着,通过创建用户表和实体类,演示了 CRUD 操作的全流程,包括查询、插入、更新和删除。最后,深入探讨了动态 SQL 和缓存机制等高级功能,帮助开发者提升数据库交互效率和代码灵活性。掌握这些内容,能显著提高 Java 编程中的数据库操作能力。
1150 4
|
3月前
|
Java 数据库连接 API
Java 对象模型现代化实践 基于 Spring Boot 与 MyBatis Plus 的实现方案深度解析
本文介绍了基于Spring Boot与MyBatis-Plus的Java对象模型现代化实践方案。采用Spring Boot 3.1.2作为基础框架,结合MyBatis-Plus 3.5.3.1进行数据访问层实现,使用Lombok简化PO对象,MapStruct处理对象转换。文章详细讲解了数据库设计、PO对象实现、DAO层构建、业务逻辑封装以及DTO/VO转换等核心环节,提供了一个完整的现代化Java对象模型实现案例。通过分层设计和对象转换,实现了业务逻辑与数据访问的解耦,提高了代码的可维护性和扩展性。
165 1
|
2月前
|
SQL Java 数据库连接
Spring、SpringMVC 与 MyBatis 核心知识点解析
我梳理的这些内容,涵盖了 Spring、SpringMVC 和 MyBatis 的核心知识点。 在 Spring 中,我了解到 IOC 是控制反转,把对象控制权交容器;DI 是依赖注入,有三种实现方式。Bean 有五种作用域,单例 bean 的线程安全问题及自动装配方式也清晰了。事务基于数据库和 AOP,有失效场景和七种传播行为。AOP 是面向切面编程,动态代理有 JDK 和 CGLIB 两种。 SpringMVC 的 11 步执行流程我烂熟于心,还有那些常用注解的用法。 MyBatis 里,#{} 和 ${} 的区别很关键,获取主键、处理字段与属性名不匹配的方法也掌握了。多表查询、动态
115 0
|
4月前
|
SQL XML Java
菜鸟之路Day33一一Mybatis入门
本文是《菜鸟之路Day33——Mybatis入门》的教程,作者blue于2025年5月18日撰写。文章介绍了MyBatis作为一款优秀的持久层框架,如何简化JDBC开发。通过创建SpringBoot工程、数据库表`user`及实体类`User`,引入MyBatis依赖并配置数据库连接信息,使用注解方式编写SQL语句实现查询所有用户数据的功能。此外,还展示了如何通过Lombok优化实体类代码,减少冗余的getter/setter等方法,提高开发效率。最后通过单元测试验证功能的正确性。
179 19
|
3月前
|
SQL Java 数据库
解决Java Spring Boot应用中MyBatis-Plus查询问题的策略。
保持技能更新是侦探的重要素质。定期回顾最佳实践和新技术。比如,定期查看MyBatis-Plus的更新和社区的最佳做法,这样才能不断提升查询效率和性能。
164 1
|
6月前
|
Java 关系型数据库 数据库连接
Javaweb之Mybatis入门程序的详细解析
本文详细介绍了一个MyBatis入门程序的创建过程,从环境准备、Maven项目创建、MyBatis配置、实体类和Mapper接口的定义,到工具类和测试类的编写。通过这个示例,读者可以了解MyBatis的基本使用方法,并在实际项目中应用这些知识。
163 11
|
8月前
|
SQL Java 数据库连接
对Spring、SpringMVC、MyBatis框架的介绍与解释
Spring 框架提供了全面的基础设施支持,Spring MVC 专注于 Web 层的开发,而 MyBatis 则是一个高效的持久层框架。这三个框架结合使用,可以显著提升 Java 企业级应用的开发效率和质量。通过理解它们的核心特性和使用方法,开发者可以更好地构建和维护复杂的应用程序。
376 29
|
6月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于注解的整合
本文介绍了Spring Boot集成MyBatis的两种方式:基于XML和注解的形式。重点讲解了注解方式,包括@Select、@Insert、@Update、@Delete等常用注解的使用方法,以及多参数时@Param注解的应用。同时,针对字段映射不一致的问题,提供了@Results和@ResultMap的解决方案。文章还提到实际项目中常结合XML与注解的优点,灵活使用两者以提高开发效率,并附带课程源码供下载学习。
543 0