本文是MyBatis注解开发的基础篇,将通过实际场景,详细介绍MyBatis注解式开发的使用,这是MyBatis很强大的一个特性,可以直接在接口方法上定义 SQL 语句,从而实现数据库的增删改查操作。
在开发之前,需要确保环境pom.xml
中添加了MyBatis相关依赖。
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.3.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.33version>
dependency>
同时,需要在 application.properties
中配置数据库连接信息:
spring.datasource.url=jdbc:mysql://localhost:3306/shop
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
使用Mybatis操作数据库,是要创建数据表对应的实体类的,这也是其优点之一。
package com.example.ecommerce.entity;
public class Product {
private Long id;
private String name;
private double price;
private int stock;
public Product() {
}
public Product(String name, double price, int stock) {
this.name = name;
this.price = price;
this.stock = stock;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
", stock=" + stock +
'}';
}
}
创建一个映射接口,使用MyBatis注解来定义对应的增删改查操作的SQL语句即可,这样可以避免我们还要写对应xml文件,同时也可以避免出现文件扫描不到的问题。
需要使用到如下注解:
@Mapper
:用于标记该接口为MyBatis的映射接口,让Spring能够自动扫描并注册。以下几个注解,可以直接在接口方法上定义 SQL 语句,从而实现数据库的增删改查操作:
@Insert
:用于定义插入操作的SQL语句。@Options
注解用于指定是否使用自动生成的主键,并指定主键属性。@Select
:用于定义查询操作的SQL语句。@Results
:用于手动指定结果集的映射关系。@Result
注解用于指定实体类属性和数据库表列的对应关系,定义之后,会将查询字段赋值到对应的类字段上。@Update
:用于定义更新操作的 SQL 语句。@Delete
:用于定义删除操作的 SQL 语句。package com.example.ecommerce.mapper;
import com.example.ecommerce.entity.Product;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface ProductMapper {
// 新增商品
@Insert("INSERT INTO product (name, price, stock) VALUES (#{name}, #{price}, #{stock})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insertProduct(Product product);
// 根据ID查询商品
@Select("SELECT * FROM product WHERE id = #{id}")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "name", column = "name"),
@Result(property = "price", column = "price"),
@Result(property = "stock", column = "stock")
})
Product selectProductById(Long id);
// 查询所有商品
@Select("SELECT * FROM product")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "name", column = "name"),
@Result(property = "price", column = "price"),
@Result(property = "stock", column = "stock")
})
List<Product> selectAllProducts();
// 更新商品信息
@Update("UPDATE product SET name = #{name}, price = #{price}, stock = #{stock} WHERE id = #{id}")
int updateProduct(Product product);
// 根据ID删除商品
@Delete("DELETE FROM product WHERE id = #{id}")
int deleteProductById(Long id);
}
如上,定义完成之后,就可以直接在对应的Service中调用了。
上面的是比较基础的增删改查,当我们有复杂的动态SQL可以使用如下几个注解@SelectProvider、@InsertProvider、@UpdateProvider 和 @DeleteProvider 来动态生成SQL语句。
使用 @SelectProvider
进行动态查询示例:
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.SelectProvider;
import java.util.List;
@Mapper
public interface ProductMapper {
@SelectProvider(type = ProductSqlProvider.class, method = "selectProductsByCondition")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "name", column = "name"),
@Result(property = "price", column = "price"),
@Result(property = "stock", column = "stock")
})
List<Product> selectProductsByCondition(@Param("name") String name, @Param("minPrice") Double minPrice, @Param("maxPrice") Double maxPrice);
}
class ProductSqlProvider {
public String selectProductsByCondition(String name, Double minPrice, Double maxPrice) {
StringBuilder sql = new StringBuilder("SELECT * FROM product WHERE 1 = 1");
if (name != null && !name.isEmpty()) {
sql.append(" AND name LIKE CONCAT('%', #{name}, '%')");
}
if (minPrice != null) {
sql.append(" AND price >= #{minPrice}");
}
if (maxPrice != null) {
sql.append(" AND price <= #{maxPrice}");
}
return sql.toString();
}
}
← 上一篇 Java进阶——常用类及常用方法详解 |
记得点赞、关注、收藏哦!
|
下一篇 Java进阶——数组超详细整理 → |