映射我有這些3代表在我的數據庫如何將多個單一對多關聯在Hibernate中
CREATE TABLE IF NOT EXISTS `User`(
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
)
CREATE TABLE IF NOT EXISTS `Project` (
`id` INT NOT NULL AUTO_INCREMENT,
`manager` INT NOT NULL,
`name` VARCHAR(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
FOREIGN KEY (`manager`) REFERENCES `User`(`id`)
)
CREATE TABLE IF NOT EXISTS `Work`(
`id` INT NOT NULL AUTO_INCREMENT,
`project_id` INT NOT NULL DEFAULT -1,
`name` VARCHAR(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
FOREIGN KEY (`project_id`) REFERENCES `Project`(`id`),
FOREIGN KEY (`creator`) REFERENCES `User`(`id`)
)
然後我想用Hibernate將它們連接起來。
這是我的java類
用戶:
// ... import code
@Entity
@Table
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column
private String name;
@OneToMany(mappedBy = "manager")
private List<Project> projects;
public User() {
}
// ... Getter & Setter code
}
項目:
// ... import code
@Entity
@Table
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column
private String name;
@ManyToOne
@JoinColumn(name = "manager")
private User manager;
public Project() {
}
// ... Getter & Setter code
}
工作:
// ... import code
public class Work {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column
private String name;
@Column(name = "project_id")
private int projectId;
@ManyToOne
@JoinColumn(name = "creator")
private User creator;
public Work() {
}
// ... Getter & Setter code
}
現在它可以工作。
但是,在項目和工作(一對多/多對一)映射關係之後,它給了我錯誤消息。
我映射做的是:
添加這些代碼到工程類:
@OneToMany(mappedBy = "project_id")
private List<Work> works;
public List<Work> getWorks() {
return works;
}
public void setWorks(List<Work> works) {
this.works = works;
}
而且這些代碼到工作類:
@ManyToOne
@JoinColumn(name = "project_id")
private Project project;
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
,並刪除@Column(name = "project_id") private int projectId;
然後它給了我錯誤信息:
Exception in thread "main" org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: database.tables.Work.project_id in database.tables.Project.works
at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:768)
at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:728)
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:70)
at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1697)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1426)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1846)
所以我想知道如何映射項目工作的關係。
這可能會幫助你:http://www.mkyong.com/hibernate/hibernate-one-to-many-relationship-example-annotation/ – jmcg
這也可以幫助你:http://stackoverflow.com/q/24257449/2357233聲明:我寫了它 – JamesENL