你的映射應該是這樣的
表結構
CREATE TABLE `person` (
`id_person` BIGINT(20) NOT NULL AUTO_INCREMENT,
`firstname` VARCHAR(50) NULL DEFAULT NULL,
`lastname` VARCHAR(50) NULL DEFAULT NULL,
`birth_date` DATE NULL DEFAULT NULL,
`cell_phone` VARCHAR(15) NULL DEFAULT NULL,
PRIMARY KEY (`id_person`)
)ENGINE=InnoDB;
CREATE TABLE `address_type` (
`id_address_type` BIGINT(10) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NULL DEFAULT NULL,
PRIMARY KEY (`id_address_type`)
)ENGINE=InnoDB;
CREATE TABLE `address` (
`id_address` BIGINT(10) NOT NULL AUTO_INCREMENT,
`fk_address_type`BIGINT(20) NULL DEFAULT NULL,
PRIMARY KEY (`id_address`),
CONSTRAINT `FK_ADDRESS_TYPE` FOREIGN KEY (`fk_address_type`) REFERENCES `address_type` (`id_address_type`),
)ENGINE=InnoDB;
CREATE TABLE `person_address` (
`id_person_address` BIGINT(10) NOT NULL AUTO_INCREMENT,
`fk_person` BIGINT(20) NULL DEFAULT NULL,
`fk_address`BIGINT(20) NULL DEFAULT NULL,
PRIMARY KEY (`id_person_address`),
CONSTRAINT `FK_PERSON` FOREIGN KEY (`fk_person`) REFERENCES `person` (`id_person`),
CONSTRAINT `FK_ADDRESS` FOREIGN KEY (`fk_address`) REFERENCES `address` (`id_address`)
)ENGINE=InnoDB;
實體類
Person.java
@Entity
@Table(name = "person",uniqueConstraints = {
@UniqueConstraint(columnNames = "id_person")})
public class Person implements Serializable {
private static final long serialVersionUID = -1798070786993154676L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_person", unique = true, nullable = false)
private Integer id;
@OneToMany(cascade=CascadeType.ALL)
@JoinTable(name="person_address", joinColumns={@JoinColumn(name="fk_person", referencedColumnName="id_person")}
, inverseJoinColumns={@JoinColumn(name="fk_address", referencedColumnName="id_address")})
private Set<Address> address;
// Getter and Setter methods
}
Address.java
@Entity
@Table(name = "address", uniqueConstraints = {
@UniqueConstraint(columnNames = "id_address")})
public class Address implements Serializable {
private static final long serialVersionUID = -6790693372846798580L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_address", unique = true, nullable = false)
private Integer addressId;
@OneToOne(mappedBy="address", cascade=CascadeType.ALL)
private AddressType addressType;
// Getter and Setter methods
}
AddressType.java
@Entity
@Table(name="address_type",uniqueConstraints = {
@UniqueConstraint(columnNames = "id_address_type")})
public class AddressType {
@Id
@Column(name="id_address_type", unique=true, nullable=false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long addressTypeId;
@OneToOne
@PrimaryKeyJoinColumn
private Address address;
// Getter and Setter methods
}
現在,當你調用getAddress()
這將返回人l與Person相關的地址然後根據地址類型對該地址進行分組,即通過調用address.getAddressType().getName()
方法。
您也可以從我的Hibernate的裸知識地址和地址類型實體之間@ManyToMany映射
對不起。我想看到的最重要的地圖是Person類中的getter(getHomeAddress():getOfficeAddresses():Address * ...)。但是,他們不在這裏。 –