我正在尝试使用EclipseLink JPA& amp;来模拟一个简单的OneToMany关系。 MySQL的。它失败了一些错误消息。任何人都可以帮助我理解它缺少什么吗?
@Entity
public class Job implements Serializable {
@Id
@GeneratedValue
private long jobId;
@OneToMany(targetEntity=Applicant.class,mappedBy="job",cascade=CascadeType.ALL)
private List<Applicant> applicant;
//Gettters and Setters
}
@Entity
public class Applicant {
@Id
@GeneratedValue
private long applicantId;
@ManyToOne
@JoinColumn(name="job_Id")
private Job job;
//Gettters and Setters
}
TestCode
Job job=new Job ();
List <Applicant> applicants=new ArrayList<Applicant>();
Applicant applicant=new Applicant();
applicants.add(applicant);
job.setApplicant(applicants);
em.persist(job);// EntityManager Reff
错误讯息:
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'job_Id' in 'field list'
答案 0 :(得分:1)
您需要在Applicant
表中添加外键列。
您Job
与@JoinColumn(name="job_Id")
的注释关系。 @JoinColumn
不是必需的,因为JPA完全取决于约定优于配置,这意味着如果您不覆盖它们,则会隐含默认值。如果没有此注释,EclipseLink将搜索名为job_jobId
(<field name>_<id column name in target table>
)的列。由于您声明加入列为job_Id
,因此您需要在Applicant
表格中包含该列。
这些数据库表应与您的实体映射一起使用(@JoinColumn(name = "job_Id")
):
TABLE JOB
JOBID (PRIMARY KEY)
TABLE APPLICANT
APPLICANTID (PRIMARY KEY)
JOB_ID (FOREIGN KEY TO JOB#JOBID)
答案 1 :(得分:0)
@Entity
public class Job implements Serializable{
@Id
@GeneratedValue
@Column(name="job_id")
private long jobId;
@OneToMany(mappedBy="job",cascade=CascadeType.ALL)
private List<Applicant> applicants;
public Job(){
applicants = new ArrayList<Applicant>();
}
public List<Applicant> getApplicants(){
//force clients through addApplicant() method to encapsulate setting both sides of relationship
return Collections.unmodifiableList(applicants);
}
public void addApplicant(Applicant applicant){
//set both sides of relationship
applicant.setJob(this);
applicants.add(applicant);
}
}
@Entity
public class Applicant {
@Id
@GeneratedValue
private long applicantId;
@ManyToOne
@JoinColumn(name="job_Id")
private Job job;
}
Job job = new Job ();
Applicant applicant = new Applicant();
job.addApplicant(applicant);
em.persist(job);