java jpa自身关联查询_使用JPA进行数据查询和关联查询

本文详细介绍了如何使用Java JPA进行数据查询和关联查询,包括一对一(OneToOne)、一对多(OneToMany)、多对一(ManyToOne)和多对多(ManyToMany)关系的建立及其实现。通过示例代码展示了在实体类中如何标记关系,并提供了自定义查询的方法。
摘要由CSDN通过智能技术生成

使用JPA进行数据查询和关联查询

在开发中经常会使用mybatis、jpa等框架来解决O/R映射技术实现数据访问。本文主要介绍使用JPA实现数据访问。

通常在关联查询的时候,表与表之前存在的关系有

OneToOne

OneToMany

ManyToOne

ManyToMany

想要理清两个表之间的关系需要根据实际场景进行区分。在建立实体类的时候,需要知道哪一个是主体。通常情况下一对多和多对一始终是以多的一方为主体的。注解在使用中“始终在非主体的一方标记自己在主体中的名称”

基本数据查询

举例:有如下几个表的关系,表之间的ER图如下:

er%E5%85%B3%E7%B3%BB%E5%9B%BE.png

1

9be8f8f764f6

image.png

一对一

Student和Sore对应的关系,score类如下:

package spring.demo.security.entity.test;

import javax.persistence.*;

/**

* Created by td on 2017/10/12.

*/

@Entity

@Table(name = "score")

public class Score {

@Id

@GeneratedValue

private Integer id;

@Column(name = "chinese_score")

private Integer chinese;

@Column(name = "math_score")

private Integer math;

//通常情况下score和student中,认为studnet是主体,我们需要在sore非主体中标记他在主体中的名字

@OneToOne(mappedBy = "score")

private Student student;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public Integer getChinese() {

return chinese;

}

public void setChinese(Integer chinese) {

this.chinese = chinese;

}

public Integer getMath() {

return math;

}

public void setMath(Integer math) {

this.math = math;

}

}

student类如下:

package spring.demo.security.entity.test;

import javax.persistence.*;

/**

* Created by td on 2017/10/12.

*/

@Entity

@Table(name = "student")

public class Student {

@Id

@GeneratedValue

private Integ

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值