【发布时间】:2015-12-22 18:05:34
【问题描述】:
在使用普通 JDBC 几个月后,我最近切换到 JPA (EclipseLink),并且正在使用 API 重建我的一个应用程序。
快速背景:我在 MySQL 数据库中有两个表。 CandidateBean 表示的表使用其主键作为 SearchCriteria 表中“Ref”列中的外键。
我想以这样一种方式检索对象,即如果我检索 CandidateBean,它会自动检索它链接到的 SearchCriteria 对象。我了解单个实体和 JPQL 查询的检索,但我很确定在 JPA 中有一种直接的方法可以做到这一点,它不像 JDBC 那样涉及多个查询/连接。
我有以下代码:
CandidateBean:
// Tells JPA that this class defines an entity to be stored in a database
@Entity
// Overrides default table name
@Table(name = "CandidateUsers")
// Maps CandidateProfile table to this entity
public class CandidateBean implements Serializable {
private static final long serialVersionUID = 1L;
// Overriding column names to match database tables
@Column(name = "FName")
private String fName;
@Column(name = "LName")
private String lName;
@Column(name = "Pass")
private String password;
@Column(name = "Email")
private String email;
// Tells JPA that the following field is the primary key for this entity
@Id
// Tells JPA to use auto-incremented values of the MySQL table as the userID
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "UserID")
private int userID = 0;
etc etc constructors/getters/setters
搜索条件:
//Tells JPA that this class defines an entity to be stored in a database
@Entity
//Overrides default table name
@Table(name = "SearchCriteria")
public class SearchCriteria implements Serializable {
private static final long serialVersionUID = 1L;
// Tells JPA that the following field is the primary key for this entity
@Id
// Tells JPA to use auto-incremented values of the MySQL table as the userID
@GeneratedValue(strategy = GenerationType.IDENTITY)
// Overriding column names to match database tables
@Column(name = "SearchID")
private int searchID;
@Column(name = "State")
private String state;
@Column(name = "Field")
private String field;
@Column(name = "Cert")
private String certification;
@Column(name = "CompDate")
private String date;
@Column(name = "School")
private String school;
@ManyToOne(optional = false)
@JoinColumn(name="Ref", referencedColumnName = "UserID")
private CandidateBean user;
etc etc constructors/getters/setters
如果我需要澄清一些事情,请告诉我。感谢您的帮助!
【问题讨论】: