SpringBoot实现ORM操作MySQL的几种方法

 更新时间:2022年02月20日 10:34:06   作者:小高写BUG  
本文主要介绍了SpringBoot实现ORM操作MySQL的几种方法,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

使用mybatis框架操作数据,在springboot框架中集成mybatis

使用步骤:

mybatis起步依赖:完成mybatis对象自动配置,对象放在容器中。

    <dependencies>
<!--        web起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<!--        mybaitis起步依赖-->
        <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>
            <scope>runtime</scope>
        </dependency>
<!--        测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

pom.xml指定把src/main/java目录中的xml文件包含到classpath中。

    <build>

<!--        resources插件-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>

        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

创建实体类Studnet

创建Dao接口StudentDao,创建一个查询学生的方法。

/**
 * @Mapper :告诉MyBatis这是dao接口,创建此接口的代理对象,
 *      位置:在类的上面。
 * **/
@Mapper
public interface StudentDao {
    Student selectById(@Param("stuId") Integer id);
}

创建Dao接口对应的Mapper文件,xml文件,写sql语句。

/**
 * @Mapper :告诉MyBatis这是dao接口,创建此接口的代理对象,
 *      位置:在类的上面。
 * **/
@Mapper
public interface StudentDao {
    Student selectById(@Param("stuId") Integer id);
}
<?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="com.firewolf.dao.StudentDao">
<!--    定义sql语句-->
    <select id="selectById" resultType="com.firewolf.model.Student">
        select id,name,age from student where id=#{stuId}
    </select>
</mapper>

创建servlet层对象,创建StudentService接口和它的实现类。去调用dao对象的方法,完成数据库的操作。

package com.firewolf.service;

public interface StudentService {
    Student queryStudent(Integer id);
}

package com.firewolf.service.impl;
@Service
public class StudentServiceImpl implements StudentService {
    @Resource
    private StudentDao studentDao;
    @Override
    public Student queryStudent(Integer id) {
        Student student=studentDao.selectById(id);
        return student;
    }
}

创建Controller对象,访问Service。

@Controller
public class StudentController {
    @Resource
    private StudentService studentService;

    @RequestMapping("/student/query")
    @ResponseBody
    public String queryStudent(Integer id){
        Student student = studentService.queryStudent(id);
        return student.toString();
    }
}

写application.properties文件。

配置数据库的连接信息

server.port=9001
server.servlet.context-path=/orm
# 连接数据库
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=991231gao
 

1.第一种方式:@Mapper

@Mapper:放在dao接口的上面,每个接口都需要使用这个注解。

/**
 * @Mapper :告诉MyBatis这是dao接口,创建此接口的代理对象,
 *      位置:在类的上面。
 * **/
@Mapper
public interface StudentDao {
    Student selectById(@Param("stuId") Integer id);
}

2.第二种方式 @MapperScan

/**
 * @MapperScan : 找到Dao接口和Mapper文件。
 *         basePackages:dao接口所在的包名
 * **/
@SpringBootApplication
@MapperScan(basePackages = {"com.firewolf.dao","com.firewolf.mapper"})
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

3.第三种方式:Mapper文件和Dao接口分开管理

现在把Mapper文件放在resources

  1. 在resources目录中创建子目录,例如mapper
  2. 把mapper文件放到mapper目录中。
  3. 在application.properties文件中,指定mapper文件的目录。
# 指定mapper文件的位置
mybatis.mapper-locations=classpath:mapper/*.xml
# mybaitis的日志
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

在pom.xml中指定目录,把resources目录中的文件,编译到目标目录中。

<!--        resources插件-->
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
        </resources>

4.事务

spring框架中的事务

管理事务的对象:事务管理器(接口,接口有很多的实现类)。

例如:使用jdbc或mybatis访问数据库,使用事务管理器:DataSourceTransactionManager

声明式事务:在xml配置文件或者使用注解说明事务控制的内容。

控制事务:隔离级别,传播行为,超时时间。

事务处理方式

  • spring框架中的@Transactional
  • aspectj框架可以在xml配置文件中,声明事务控制的内容。

springboot中使用事务:上面的两种方式都可以。

  • 在业务方法的上面加入@Transactional,加入注解后,方法有事务功能了。
  • 明确在主启动类的上面,加入@EnableTransactionManager。
@SpringBootApplication

@EnableTransactionManagement

@MapperScan(value="com.firewolf.dao")
public class Application {
   public static void main(String[] args) {
           SpringApplication.run(Application.class, args);
   }
}

例子:

/**
 * @Transactional: 表示方法的有事务支持
 *       默认:使用库的隔离级别, REQUIRED 传播行为; 超时时间  -1
 *       抛出运行时异常,回滚事务
 */
@Transactional
@Override
public int addStudent(Student student) {
    System.out.println("业务方法addStudent");
    int rows  =  studentDao.insert(student);
    System.out.println("执行sql语句");

    //抛出一个运行时异常, 目的是回滚事务
    //int m   = 10 / 0 ;

    return rows;
}

到此这篇关于SpringBoot实现ORM操作MySQL的几种方法的文章就介绍到这了,更多相关SpringBoot ORM操作MySQL内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java设计模式之装饰者模式详解和代码实例

    Java设计模式之装饰者模式详解和代码实例

    这篇文章主要介绍了Java设计模式之装饰者模式详解和代码实例,Decorator模式(别名Wrapper):动态将职责附加到对象上,若要扩展功能,装饰者提供了比继承更具弹性的代替方案,需要的朋友可以参考下
    2014-09-09
  • 解决dubbo启动报服务注册失败Failed to register dubbo

    解决dubbo启动报服务注册失败Failed to register dubbo

    这篇文章主要介绍了解决dubbo启动报服务注册失败Failed to register dubbo问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-12-12
  • SpringBoot实现数据预热的方式小结

    SpringBoot实现数据预热的方式小结

    这里用到的数据预热,就是在项目启动时将一些数据量较大的数据加载到缓存中(笔者这里用的Redis),那么在项目启动有哪些方式可以实现数据预热呢,本文就来给大家讲讲几种实现数据预热的方式,需要的朋友可以参考下
    2023-09-09
  • Spring @Conditional注解原理解析

    Spring @Conditional注解原理解析

    这篇文章主要介绍了Spring @Conditional注解原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • 解决SpringBoot整合Mybatis扫描不到Mapper的问题

    解决SpringBoot整合Mybatis扫描不到Mapper的问题

    这篇文章主要介绍了解决SpringBoot整合Mybatis扫描不到Mapper的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-04-04
  • Maven远程仓库地址修改实现解析

    Maven远程仓库地址修改实现解析

    这篇文章主要介绍了Maven远程仓库地址修改实现解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • SpringBoot启动时运行特定代码的多种方式小结

    SpringBoot启动时运行特定代码的多种方式小结

    SpringBoot提供了多种方式在应用程序启动时运行特定的代码,包括CommandLineRunner、ApplicationRunner、@PostConstruct、InitializingBean、事件机制和自定义注解等,下面就来具体介绍一下
    2025-01-01
  • IntelliJ IDEA的代码搁置功能实现

    IntelliJ IDEA的代码搁置功能实现

    本文主要介绍了IntelliJ IDEA的代码搁置功能实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-01-01
  • JDK8新特性之判空遍历写法

    JDK8新特性之判空遍历写法

    这篇文章主要介绍了JDK8新特性之判空遍历写法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-10-10
  • 基于Springboot+Mybatis对数据访问层进行单元测试的方式分享

    基于Springboot+Mybatis对数据访问层进行单元测试的方式分享

    本文将介绍一种快高效、可复用的解决测试方案——对数据访问层做单元测试,文章通过代码示例介绍的非常详细,具有一定的参考价值,需要的朋友可以参考下
    2023-07-07

最新评论