栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JPA 上手指南

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JPA 上手指南

JPA

版本:spring-boot-starter-data-jpa-2.7.2

[2022-08-09 18:18:03]

前言:

作为 MyBatis 的重度用户,当新项目用到新的 JPA 的持久化层技术时,完全没接触过而又没有拿来即用的参考文档时怎么办呢?下面的文章应该会对你有帮助

注:以下出现的单测均通过上级验证(建表语句见文末)

熟悉 MyBatis 的知道,MyBatis 是强大的,它是一款优秀的 ORM 框架,支持原生的 SQL 语句等等

JPA 听说过最出名的就是“不用写 sql 语句”,那么它是怎么做到的。

回顾起 mapper 文件,会自然想到,那它是怎么实现 ① mapper 的实体类和基类的一一映射关系、② Bean属性和表字段之间的映射、查询方法的…

跟着这个框架走可以帮助我们更快速地认识 JPA 的语法

1.实体类

过去需要继承一个基类,但是不适合测试,现在利用注解@Entity代替了

2.对象关系映射

可以像 MyBatis 一样用专门的配置文件 xml 配置,也可以用注解的方法配置 [从字段到属性] 之间的映射关系,也就是 jpa 中的 @Column

3.其它属性描述

注解@Id和@GeneratedValue是告诉JPA主键和自动递增的信息,既可以加在get方法上也可以加在字段上,建议加在字段上

依赖:

spring-boot-starter-data-jpa
com.h2database.h2	# (创建基于内存的数据库/测试用)
lombok				# 缩写setter/getter用
1.取出查询实体

repository.findById(1).get()从Optional 里取出实体类

Optional byId = repository.findById(1);
ProductCategory productCategory = repository.findById(1).get();
2.正确的修改姿势

先查出来,然后对结果按需设置,相当于MyBatis的按需更新。

// [2022-08-05 10:02:05]
@Test
public void testUpdate() {
    ProductCategory productCategory = repository.findById(1).get();
    productCategory.setCategoryName("热销磅单///");
    repository.save(productCategory);
}
附:实体类的元素

以一张商品类别表举例

@Data
@AllArgsConstructor		// 构造对象用
@NoArgsConstructor		// 构造对象用
@Entity    // JPA
@Table(name="product_category")		// 绑定表,也方便查看映射表(非必填)如果命名严格按照驼峰的话
public class ProductCategory implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY) // 自动递增的字段
    @Column(name="category_id")		// (非必填)如果命名严格按照驼峰的话
    private Integer categoryId;

    @Column(name="category_type")
    private Integer categoryType;

    	
    @Column(name="category_name")	// (非必填)
    private String categoryName;

    
    @Column(name="create_time")		// (非必填)
    private Date createTime;

    
    @Column(name="update_time")		// (非必填)
    private Date updateTime;

}
3.常用方法 1.count()
@Test
    public void testCount() {
        long count = repository.count();
    }
2.existById()
@Test
    public void testExistById() {
        boolean b = repository.existsById(2);
    }
3.saveAll()
@Test
    public void testSaveAll() {
        List list = mockList();
        repository.saveAll(list);
        List all = repository.findAll();
        all.forEach(System.out::println);
    }
4.mybatis没有的findAllById(List)
@Test
    public void testFindAllById() {
        Integer[] ints = {1,3,4,5,6,7};
        List list = new ArrayList<>(Arrays.asList(ints));
        List allById = repository.findAllById(list);
        allById.forEach(System.out::println);
    }
4.+非主键字段的in查询

主键字段:category_id - findAllById()

非主键:category_type 也有对应的智能匹配生成

	repository
	
    List findByCategoryTypeIn(List typeIdList);
	Test
	
    @Test
    public void testFindByCategoryTypeIn() {
        Integer[] ints = {1, 10};
        List byCategoryIn = repository.findByCategoryTypeIn(Arrays.asList(ints));
        System.out.println(byCategoryIn);
    }

1.按照findByFieldNameBy(List list)的规则定义抽象方法

2.使用

相当于 MyBatis 的