ORM操作MySQL

ORM操作MySQL

本篇主要讲解MyBatis框架操作数据库,通过SpringBoot + MyBatis实现对数据库的操作

我们以学生表为例,表结构如下 :
表结构

mapper文件的方式

使用步骤

  1. MyBatis起步依赖 : 完成MyBatis对象的自动配置,对象放在容器中
  2. pom.xml指定把src/main/java目录中的xml文件包含到classpath中
    方式如下 :
    在build标签中加入下面的语句
		<resources>
			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**/*.xml</include>
				</includes>
			</resource>
		</resources>
  1. 创建实体类Student
  2. 创建Dao接口 StudentDao,创建一个查询学生的方法
  3. 创建Dao接口对应的Mapper文件,xml文件写Sql语句
<?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="org.zjb.dao.StudentDao">
    
    <!--定义sql语句-->
    <select id="selectById" resultType="org.zjb.model.Student">
        select id,name,age from student where id=#{stuId}
    </select>

</mapper>
  1. 创建Service层对象,创建StudentService接口和其实现类,调用dao对象的方法
  2. 创建Controller对象,访问Service
  3. 写application.properties文件
    配置数据库的连接信息

注解的方式

上面是使用mapper.xml文件的方式来执行sql的,下面是更简单的方式,就是使用注解的方式
文件结构如下 :
文件结构

  1. MyBatis依赖加入,可以在构建项目的时候就选择加入依赖
  2. 编写实体类student
public class Student {

    private Integer id;
    private String name;
    private Integer age;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    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 Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
  1. 创建Dao接口 StudentDao,并在这个接口上使用注解的方式指定要执行的sql语句
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.zjb.model.Student;

/**
 * @Mapper : 告诉MyBatis这是dao接口,需要创建代理对象
 *     位置 : 类的上面
 */
@Mapper
public interface StudentDao {

    @Select("select id,name,age from student where id = ${stuId}")
    Student selectById(@Param("stuId") Integer id);
}
  1. 创建Service层对象,创建StudentService接口和其实现类,调用dao对象的方法
    service接口的实现类
import org.springframework.stereotype.Service;
import org.zjb.dao.StudentDao;
import org.zjb.model.Student;
import org.zjb.service.StudentService;

import javax.annotation.Resource;

@Service
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentDao studentDao;

    @Override
    public Student queryStudent(Integer id) {
        return studentDao.selectById(id);
    }
}
  1. 创建Controller对象,访问Service
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.zjb.service.StudentService;

import javax.annotation.Resource;

@Controller
public class StudentController {

    @Resource
    private StudentService studentService;


    @RequestMapping("/student/query")
    @ResponseBody
    public String queryStudent(Integer id) {
        return studentService.queryStudent(id).toString();
    }
}
  1. 写application.properties文件
    配置数据库的连接信息
    application.properties
server.port=8081
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=123456
  1. 测试结果
    结果

@Mapper和@MapperScan

@Mapper注解位置在每个dao接口之上,每个接口都需要使用这个注解,但是有时候我们的dao类太多,一个一个写很麻烦,现在就需要使用@MapperScan注解
@MapperScan的使用方式是,在主启动类上添加包扫描,如下:

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan(basePackages = "org.zjb.dao")
public class Application {

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

}

basePackages属性的值是一个数组可以为

@MapperScan(basePackages = {"org.zjb.dao", "org.zjb.Mapper"})

Mapper文件和dao接口分离

实际开发中,我们可能会将Mapper文件和dao接口分离,这样文件结构更加分明
分离后的文件结构如下 :
分离后的文件结构
此时我们需要在application.properties文件中指定打包后的mapper文件的位置
需要添加如下语句 :

#指定mapper文件的位置
mybatis.mapper-locations=classpath:mapper/*.xml

开启MyBatis日志

在application.properties中加入下面语句即可

#开启MyBatis日志
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

事务

SpringBoot使用事务非常简单,底层依然采用的是Spring本身提供的事务管理
spring框架中的事务

  1. 管理事务的对象 : 事务管理器(接口,有很多的实现类,对应不同数据库)
    例如 : 使用JDBC或者MyBatis访问数据库,使用的事务管理器就是 : DataSourceTransactionManager
  2. 声明式事务 : 在xml的配置文件或者注解说明事务控制的内容
    控制事务 : 隔离级别,传播行为,超时时间
  3. 事务的处理方式 :
    1. spring框架中的@Transactional
    2. aspectj框架可以在xml配置文件中声明事务控制的内容

SpringBoot中使用事务 : 上面的方式都可以使用

  1. 在业务方法上面加入@Transactional,方法就有事务功能了.
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zjb.dao.StudentMapper;
import org.zjb.model.Student;
import org.zjb.service.StudentService;

import javax.annotation.Resource;

@Service
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentMapper studentDao;

    /**
     * @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;
    }
}
  1. 明确的在主启动类的上面,加入@EnableTransactionManager
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @EnableTransactionManagement表示启用事务管理器,也可以不加
 */
@SpringBootApplication
@EnableTransactionManagement
@MapperScan(basePackages = "org.zjb.dao")
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值