Spring整合Mybatis

简介: Spring整合Mybatis

一:导入依赖

在我们创建一个Maven项目时,可以在pom.xml文件下导入以下依赖:

1.mybatis依赖

1.  <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>

2.spring-jdbc

 <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.31</version>
        </dependency>

3.mybatis-spring

 <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>

二:建立配置类

0.

前置工作

在dao包和service包下建立有关的接口和实现类

dao包:

package com.lcyy.dao;
 
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
 
import java.util.List;
 
public interface AccountDao {
 
    @Insert("insert into tbl_account(name,money)values(#{name},#{money})")
    void save(Account account);
 
    @Delete("delete from tbl_account where id = #{id} ")
    void delete(Integer id);
 
    @Update("update tbl_account set name = #{name} , money = #{money} where id = #{id} ")
    void update(Account account);
 
    @Select("select * from tbl_account")
    List<Account> findAll();
 
    @Select("select * from tbl_account where id = #{id} ")
    Account findById(Integer id);
}
package com.lcyy.dao;
 
public class Account {
    private Integer id;
    private String name;
    private String money;
 
    public Account(){}
 
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getMoney() {
        return money;
    }
 
    public void setMoney(String money) {
        this.money = money;
    }
 
    public Account(Integer id, String name, String money) {
        this.id = id;
        this.name = name;
        this.money = money;
    }
 
    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money='" + money + '\'' +
                '}';
    }
}

service包:

package com.lcyy.service;
 
import com.lcyy.dao.Account;
 
import java.util.List;
 
public interface AccountService {
    void save(Account account);
 
    void delete(Integer id);
 
    void update(Account account);
 
    List<Account> findAll();
 
    Account findById(Integer id);
}
package com.lcyy.service.impl;
 
import com.lcyy.dao.Account;
import com.lcyy.dao.AccountDao;
import com.lcyy.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.util.List;
 
@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;
 
    public void save(Account account) {
        accountDao.save(account);
    }
 
    public void update(Account account){
        accountDao.update(account);
    }
 
    public void delete(Integer id) {
        accountDao.delete(id);
    }
 
    public Account findById(Integer id) {
        return accountDao.findById(id);
    }
 
    public List<Account> findAll() {
        return accountDao.findAll();
    }
}

1.

在config包下建立一个MybatisConfig的类

2.

创建JdbcConfig配置DataSource数据源

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/spring_db?useSSL=false
jdbc.username=root
jdbc.password=zhien0516
package com.lcyy.config;
 
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
 
import javax.sql.DataSource;
 
//@Configuration
public class JdbcConfig {
//    @Value("druid")
//    private String age;
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
 
    @Bean("dataSource")
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
//        System.out.println("我是德鲁伊"+age);
        return ds;
    }
}

3.

创建MybatisConfig整合mybatis

import org.springframework.context.annotation.Configuration;
 
import javax.sql.DataSource;
 
@Configuration
public class MybatisConfig {
 
    //创建工厂
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setTypeAliasesPackage("com.lcyy.damain");
        sessionFactoryBean.setDataSource(dataSource);
        return sessionFactoryBean;
    }
 
    //扫包
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.lcyy.dao");
        return mapperScannerConfigurer;
    }
 
}

4.

定义测试类进行测试

import com.lcyy.config.SpringConfig;
import com.lcyy.dao.Account;
import com.lcyy.service.AccountService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 
public class DataSource {
    public static void main(String[] args) {
        //获取ioc容器
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        //根据类型获取bean,并强制转换为DataSource类型
//        Object ctxBean =  ctx.getBean("dataSource");
//        System.out.println(ctxBean);
        AccountService ctxBean = ctx.getBean(AccountService.class);
        Account ac = ctxBean.findById(1);
        System.out.println("ac = " + ac);
    }
}

5.

测试结果

数据库:

三:总结

以上就是用spring整合mybatis的步骤!希望对读者有所帮助,后续我将继续更新有关spring的知识!!!

相关文章
|
11月前
|
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`
693 0
|
8月前
|
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`注解完成整合
1417 1
Spring boot 使用mybatis generator 自动生成代码插件
|
8月前
|
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对象模型实现案例。通过分层设计和对象转换,实现了业务逻辑与数据访问的解耦,提高了代码的可维护性和扩展性。
340 1
|
7月前
|
SQL Java 数据库连接
Spring、SpringMVC 与 MyBatis 核心知识点解析
我梳理的这些内容,涵盖了 Spring、SpringMVC 和 MyBatis 的核心知识点。 在 Spring 中,我了解到 IOC 是控制反转,把对象控制权交容器;DI 是依赖注入,有三种实现方式。Bean 有五种作用域,单例 bean 的线程安全问题及自动装配方式也清晰了。事务基于数据库和 AOP,有失效场景和七种传播行为。AOP 是面向切面编程,动态代理有 JDK 和 CGLIB 两种。 SpringMVC 的 11 步执行流程我烂熟于心,还有那些常用注解的用法。 MyBatis 里,#{} 和 ${} 的区别很关键,获取主键、处理字段与属性名不匹配的方法也掌握了。多表查询、动态
225 0
|
8月前
|
SQL Java 数据库
解决Java Spring Boot应用中MyBatis-Plus查询问题的策略。
保持技能更新是侦探的重要素质。定期回顾最佳实践和新技术。比如,定期查看MyBatis-Plus的更新和社区的最佳做法,这样才能不断提升查询效率和性能。
439 1
|
SQL Java 数据库连接
对Spring、SpringMVC、MyBatis框架的介绍与解释
Spring 框架提供了全面的基础设施支持,Spring MVC 专注于 Web 层的开发,而 MyBatis 则是一个高效的持久层框架。这三个框架结合使用,可以显著提升 Java 企业级应用的开发效率和质量。通过理解它们的核心特性和使用方法,开发者可以更好地构建和维护复杂的应用程序。
771 29
|
11月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于注解的整合
本文介绍了Spring Boot集成MyBatis的两种方式:基于XML和注解的形式。重点讲解了注解方式,包括@Select、@Insert、@Update、@Delete等常用注解的使用方法,以及多参数时@Param注解的应用。同时,针对字段映射不一致的问题,提供了@Results和@ResultMap的解决方案。文章还提到实际项目中常结合XML与注解的优点,灵活使用两者以提高开发效率,并附带课程源码供下载学习。
891 0
|
11月前
|
Java 数据库连接 数据库
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——MyBatis 介绍和配置
本文介绍了Spring Boot集成MyBatis的方法,重点讲解基于注解的方式。首先简述MyBatis作为持久层框架的特点,接着说明集成时的依赖导入,包括`mybatis-spring-boot-starter`和MySQL连接器。随后详细展示了`properties.yml`配置文件的内容,涵盖数据库连接、驼峰命名规范及Mapper文件路径等关键设置,帮助开发者快速上手Spring Boot与MyBatis的整合开发。
1677 0
|
SQL JavaScript Java
Spring Boot 3 整合 Mybatis-Plus 实现数据权限控制
本文介绍了如何在Spring Boot 3中整合MyBatis-Plus实现数据权限控制,通过使用MyBatis-Plus提供的`DataPermissionInterceptor`插件,在不破坏原有代码结构的基础上实现了细粒度的数据访问控制。文中详细描述了自定义注解`DataScope`的使用方法、`DataPermissionHandler`的具体实现逻辑,以及根据用户的不同角色和部门动态添加SQL片段来限制查询结果。此外,还展示了基于Spring Boot 3和Vue 3构建的前后端分离快速开发框架的实际应用案例,包括项目的核心功能模块如用户管理、角色管理等,并提供Gitee上的开源仓库
2805 11
|
前端开发 Java 数据库连接
Java后端开发-使用springboot进行Mybatis连接数据库步骤
本文介绍了使用Java和IDEA进行数据库操作的详细步骤,涵盖从数据库准备到测试类编写及运行的全过程。主要内容包括: 1. **数据库准备**:创建数据库和表。 2. **查询数据库**:验证数据库是否可用。 3. **IDEA代码配置**:构建实体类并配置数据库连接。 4. **测试类编写**:编写并运行测试类以确保一切正常。
656 2

热门文章

最新文章