温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringBoot实现ORM操作MySQL的方法有哪些

发布时间:2022-02-21 09:28:22 来源:亿速云 阅读:115 作者:iii 栏目:开发技术

这篇文章主要介绍了SpringBoot实现ORM操作MySQL的方法有哪些的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇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的方法有哪些”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI