简介
-
通过maven_springboot_mybatis_mysql联动的基础写法,理解这套流程。
-
个人观点:Mybatis系列是目前java访问数据库最好的方式。更进一步自动生成Sql语句的Hibernate等方式,在生成质量和操作便捷性上,尤其跟EF Core相比,还是差点意思。
原理
-
MyBatis 官方提供 mybatis-spring-boot-starter,用来和 Spring Boot 整合。
-
本例中,MyBatis通过mysql-connector-j驱动,操作MySql数据库。(这也是后面例子引入两个依赖的原因)
-
MyBatis 的使用,主要是把 Java 方法调用与 SQL 语句进行映射,让开发者以面向对象的方式执行 SQL。体现在后面的“实体”和“映射”两个文件上。
操作步骤
- 数据库准备:数据库d1,表t1。
create table t1(xm nvarchar(10),nl tinyint);
insert into t1 values('zs',20);
insert into t1 values('ls',18);
- 项目准备:新建spring boot项目,maven,java(jdk25), v4.1.1, jar, Properties。
pom依赖:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>26.7.0</version>
</dependency>
- 配置数据源:在
resources/application.properties中,写入数据源信息:
# JDBC URL
spring.datasource.url=jdbc:mysql://localhost:3306/d1?useSSL=false
# 用户名
spring.datasource.username=root
# 密码
spring.datasource.password=123456
- 实体模型:表示表中的一条记录。
其中,访问器和构造函数,可以由简单的IDE操作自动实现
package com.example.demo.Entities;
public class t1 {
String xm;
int nl;
public t1() {
}
public t1(String xm, int nl) {
this.xm = xm;
this.nl = nl;
}
public String getXm() {
return xm;
}
public int getNl() {
return nl;
}
public void setXm(String xm) {
this.xm = xm;
}
public void setNl(int nl) {
this.nl = nl;
}
public String toString() {
return "t1{xm='" + xm + "', nl=" + nl + "}";
}
}
- java和Sql的映射:
这里采用注解形式,把Sql和对应的java方法都写在了java文件里。
另一种常见的写法是把Sql语句写在xml文件里,写起来麻烦一点,但在处理复杂sql的时候会略有优势。感兴趣的话自己研究。
package com.example.demo.Mapper;
import java.util.List;
import org.apache.ibatis.annotations.*;
import com.example.demo.Entities.t1;
@Mapper
public interface t1s {
/**
* 查询所有记录
*/
@Select("SELECT xm, nl FROM t1")
//列名和属性名拼写相同,可以不进行以下说明
@Results({
@Result(column = "xm", property = "xm"),
@Result(column = "nl", property = "nl")
})
List<t1> findAll();
/**
* 根据姓名查询
*/
@Select("SELECT xm, nl FROM t1 WHERE xm = #{xm}")
t1 findByXm(String xm);
/**
* 插入数据
*/
@Insert("INSERT INTO t1(xm, nl) VALUES(#{xm}, #{nl})")
int insert(t1 t1);
/**
* 更新数据
*/
@Update("UPDATE t1 SET nl = #{nl} WHERE xm = #{xm}")
int update(t1 t1);
/**
* 删除数据
*/
@Delete("DELETE FROM t1 WHERE xm = #{xm}")
int deleteByXm(String xm);
}
- 主程序调用
package com.example.demo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.demo.Mapper.t1s;
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
t1s myt;
public DemoApplication(t1s t) {
myt = t;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
public void run(String... t)
{
System.out.println(myt.findAll().toString());
}
}
mvn spring-boot:run运行结果:
[t1{xm='zs', nl=20}, t1{xm='ls', nl=18}]
- 这里仅实现了最简单的数据库操作。稍微复杂的业务,可能需要这些基础操作进行组合。通常会建立一个服务层(Services文件夹/包),来调用这些简单功能。例如:
package com.example.demo.Services;
import org.springframework.stereotype.Component;
import com.example.demo.Entities.t1;
import com.example.demo.Mapper.t1s;
@Component
public class T1 {
t1s myT1s;
public T1(t1s myT1s) {
this.myT1s = myT1s;
}
//交换两个人的年龄
public void swapNl(String x,String y)
{
t1 a,b;
int t;
a=myT1s.findByXm(x);
b=myT1s.findByXm(y);
t=a.getNl();
a.setNl(b.getNl());
b.setNl(t);
myT1s.update(a);
myT1s.update(b);
}
}
提醒:太复杂的逻辑,没必要在sql语句层面硬刚。到这里,用程序处理,可能会更舒适。
相应的,主程序修改为:
package com.example.demo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.demo.Mapper.t1s;
import com.example.demo.Services.T1;
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
//基础_表操作
t1s myt;
//业务_表操作
T1 myT;
public DemoApplication(t1s t,T1 T) {
myt = t;
myT=T;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
public void run(String... t)
{
myT.swapNl("zs","ls");
System.out.println(myt.findAll().toString());
}
}
结果略。
小结
-
实体类中的无参构造函数和setter访问器,用于从数据库中查询数据(框架new不带值的对象,用数据库返回值填充);有参构造和getter访问器,用于增/改数据(框架new有初始值的对象,读出值,拼接sql语句,操作数据库)。
-
为了简化设置、避免基础java-sql映射的编写,国人在Mybatis的基础上,开发了Mybatis-Plus框架(简称MP),国内热度很高。
-
本文旨在跑通Mybatis框架访问数据库的流程。稍复杂些表(主键、自增等等)以及Sql语句的用法,Mybatis也支持。自行扩充。
浙公网安备 33010602011771号