SpringBoot 04: springboot中应用orm操作mysql
Mapper文件和Dao接口分开管理
- 创建SpringBoot项目时勾选mybatis,mysql起步依赖
- 可以完成mybatis对象的自动配置, 将对象放在容器中
- 在resources目录中创建子目录(自定义的名称) , 例如mapper
- 把后续添加的mapper文件放到此mapper目录中
- 在application.properties文件中,指定mapper文件的目录并指定数据库连接的相关配置
#配置应用端口与上下文
server.port=9090
server.servlet.context-path=/orm
#springboot配置数据库连接
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://ip:3306/数据库名?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
spring.datasource.username=XXX
spring.datasource.password=YYY
#指定mapper配置文件的存放路径
mybatis.mapper-locations=classpath:mapper/*.xml
#打印数据库操作日志
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
- 在pom.xml中指定 把resources目录中的文件 , 编译到目标目录中
<build>
<!--resources插件-->
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
</build>
- 创建实体类Student
package com.example.web.model;
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;
}
public Student(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public Student() {
}
}
- 创建Dao接口: StudentDao,创建一个查询学生的方法
package com.example.web.dao;
import com.example.web.model.Student;
import org.apache.ibatis.annotations.Param;
public interface StudentDao {
Student selectStudentById(@Param("stuId") Integer id);
}
- 创建Dao接口对应的StudentDao.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="com.example.web.dao.StudentDao">
<!--定义sql语句-->
<select id="selectStudentById" resultType="com.example.web.model.Student">
select id,name,age from student where id=#{stuId}
</select>
</mapper>
- 在SpringBoot主启动类上添加@MapperScan,对Mapper接口进行扫描,也就是这里的Dao接口
package com.example;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages = {"com.example.web.dao"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
- 创建Service层对象,创建StudentService接口和他的实现类, 调用dao对象的方法,完成数据库的操作
//service层接口
package com.example.web.service;
import com.example.web.model.Student;
public interface StudentService {
Student queryStudentById(Integer id);
}
//service层实现类
package com.example.web.service.impl;
import com.example.web.dao.StudentDao;
import com.example.web.dao.StudentNameDao;
import com.example.web.model.Student;
import com.example.web.service.StudentService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class StudentServiceImpl implements StudentService {
@Resource
private StudentDao studentDao;
@Override
public Student queryStudentById(Integer id) {
return studentDao.selectStudentById(id);
}
}
- 创建Controller对象,访问Service
package com.example.web.controller;
import com.example.web.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
@Controller
public class StudentController {
//service层的接口类型的变量
@Resource
private StudentService studentService;
@RequestMapping("/queryStudent.do")
@ResponseBody
public String queryStudent(Integer id){
return studentService.queryStudentById(id).toString();
}
}
事务控制
Spring框架中的事务
-
管理事务的对象:事务管理器(是一个接口,而且有很多的实现类)
- 例如:使用Jdbc或mybatis访问数据库,使用的事务管理器:DataSourceTransactionManager
-
声明事务: 在xml配置文件(声明式事务)或者使用注解(注解式事务)说明事务控制的内容
-
控制事务: 隔离级别,传播行为,超时时间
-
事务处理方式
- Spring框架中的@Transactional
- aspectj框架可以在xml配置文件中,声明事务控制的内容
SpringBoot中事务处理方式
-
上述的两种事务处理方式SpringBoot都支持
-
在业务方法的上面加入@Transactional, 加入注解后,方法有事务功能了
-
更明确的可以在主启动类的上面加入@EnableTransactionManager
-
代码示例
/**
* @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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术