使用JPA进行数据查询和关联查询
在开发中经常会使用mybatis、jpa等框架来解决O/R映射技术实现数据访问。本文主要介绍使用JPA实现数据访问。
通常在关联查询的时候,表与表之前存在的关系有
OneToOne
OneToMany
ManyToOne
ManyToMany
想要理清两个表之间的关系需要根据实际场景进行区分。在建立实体类的时候,需要知道哪一个是主体。通常情况下一对多和多对一始终是以多的一方为主体的。注解在使用中“始终在非主体的一方标记自己在主体中的名称”
基本数据查询
举例:有如下几个表的关系,表之间的ER图如下:
1
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