环境:
我决定重新解释这些问题。
有2个表:
public company
{
private Long id;
private Long name;
private address table_address;
}
public address
{
private Long id;
private String address;
private Long company_id;
}
注意:两个表id都是顺序的,没有相关性。 table.address.company_id
除外是公司的外键。
如何做映射?我期望的结果是:
"company":{
"id":4,
"name":"company name",
"address":{
"id":3,
"address":"anywhere",
"company_id":4
}
}
有人可以教我这个,如何映射这2张表吗?
答案 0 :(得分:6)
您想要的是Company
和Address
只需将@OneToOne
注释添加到公司类的table_address字段:
public class Address {
@Id
@GeneratedValue
private Long id;
private String address;
@OneToOne
@PrimaryKeyJoinColumn
private Company company;
//getters and setters
}
public class Company {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToOne(mappedBy = "company",cascade = CascadeType.ALL)
private Address companyAddress;
//getters and setters
}
<子>
除了问题:
尊重java命名约定,在你的情况下,类名应该以大写字母开头,也应该以变量名中的下一个字开头。即公司应公司且地址应地址,private address table_address;
更改为private Address companyAddress;
}
子>
更新了解决方案
public class Address {
@Id
@GeneratedValue
private Long id;
private String address;
@OneToOne
@JoinColumn(name = "company_id")
private Company company;
//getters and setters
}
public class Company {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToOne(mappedBy = "company",cascade = CascadeType.ALL)
private Address companyAddress;
//getters and setters
}
来自stupidfrog:如果你使用@PrimaryKeyJoinColumn,则id加入错误。 id连接主要但不是地址表company_id
这是来自hibernate的引用 http://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/OneToOne.html 例1
答案 1 :(得分:1)
您应该创建两个实体类,如下所示
公司实体
@Entity
@Table(name = "YOUR TABLE NAME")
public company{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "COMPANY_ID")
private Long id;
@Column(name = "NAME")
private Long name;
@JoinColumn(name = "ADDRESS_ID")
@OneToOne(optional = false)
private address table_address;
}
ADDRESS ENTITY
@Entity
@Table(name = "YOUR TABLE NAME")
public address{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
private Long id;
@Column(name = "ADDRESS")
private String address;
@JoinColumn(name = "COMPANY_ID")
@OneToOne(optional = false)
private Long company_id;
}
希望这有帮助