Hibernate:使用OneToMany而不实际使用任何主/外键关系

时间:2016-02-17 14:25:18

标签: java mysql hibernate

我看过几百个帖子,与我的帖子不太相似:(

请考虑以下情况。

Mysql Schema:

create table parent(
id int,
col1 int,
col2 int,
primary key(id)
)

create table child(
id int,
col1 int,
col2 int,
primary key(id)
)

请注意,父与母之间没有显式/关键关系;儿童桌。

现在,我想要的是获取具有相同值'col1'和amp;的所有'子'对象。提取'父'时'col2'沿着[单向映射就足够了]。

我试过的Hibernate实体的排序,

@Entity
public class parent{

@Id
private int id;

@Column
private int col1;

@Column
private int col2;

@OneToMany
@JoinColumns({
    @JoinColumn(name = "col1"),
    @JoinColumn(name = "col2")
})
private List<Child> children;

/**
Other logic goes here..
**/

}

和Child实体一样,

@Entity
public class Child{

@Id
private int id;

@Column
private int col1;

@Column
private int col2;

/**
Other logic goes here..
**/
}

结果: Hibernate错误报告“来自'Parent'的外键引用'Child'的列数错误。应为1”

我认为这是因为@JoinColumn只能使用“id”

来完成

问题:

1)hibernate的所有@OneToMany @ManyToOne等是否需要表/实体之间的显式/键引用[由@Id注释]?

2)我该怎么做才能做到这一点?

2 个答案:

答案 0 :(得分:0)

这里TableA与TableB具有OneToMany关系,即TableA中的一条记录可以在TableB中具有多条记录。由于TableA中的col1在TableB的col1中被称为外键。下面的JPA代码成功获取了所有结果。

DROP table x.TableA;
CREATE TABLE x.TableA (
    Id BIGINT IDENTITY(1,1) NOT NULL,
    col1 varchar(30) NOT NULL,
    CONSTRAINT PK_col1 PRIMARY KEY(col1) 
);

DROP table x.TableB;
CREATE TABLE x.TableB ( 
    Id BIGINT IDENTITY(1,1)NOT NULL,
    col1 varchar(30) NOT NULL,
    col2 varchar(10) NULL
);

ALTER TABLE x.TableB
   ADD CONSTRAINT FK_TableB_col1 FOREIGN KEY (col1)
      REFERENCES x.TableA (col1)
;

@Entity
@Table(name = "TableA", schema = "x")
public class ClassA implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column(name = "col1")
  private String col1;


  @OneToMany(
      cascade = {CascadeType.ALL},
      orphanRemoval = true,
      fetch = FetchType.EAGER)
  @JoinColumn(name = "col1", referencedColumnName = "col1")
  private List<ClassB> objB = new ArrayList<>();
}

----------------------------------


@Entity
@Table(name = "TableB", schema = "x")
public class ClassB implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column(name = "col1")
  private String col1;

  @Column(name = "col2")
  private String col2;

}

答案 1 :(得分:-1)

尝试:
  @OneToMany @JoinColumns({ @JoinColumn(name = "col1", referencedColumnName="col1"), @JoinColumn(name = "col2", referencedColumnName="col2") })