注解:【有连接表的】Hibernate单向N->N关联

Person与Address关联:单向N->N,【有连接表的】

           #和单向1->N关联代码完全相同,控制关系的一端需要增加一个set类型的属性,被关联的持久化实例以集合形式存在。

           #N->N关联,需要使用@ManyToMany注解来修饰待代表关联实体的集合属性。

           #@JoinTable注解的inverseJoinColumn属性所指定的@JoinColumn中unique=false或去掉。 

Person.Java

package org.crazyit.app.domain;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name = "Person_inf")
public class Person {

@Column(name = "person_id")
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

private String name;

private Integer age;

// 单向1->N:N对N关联关系
// 定义该person实体关联的address实体
@ManyToMany(targetEntity = Address.class // 指定关联对象
, cascade = CascadeType.ALL// 指定级联方式 。
)
// 定义连接表中名为person_id的外键列,该外键列参照当前实体对应表的主键列
@JoinTable(name = "person_address", // 指定连接表
joinColumns = @JoinColumn(name = "person_id", //
referencedColumnName = "person_id") , //
//定义连接表中名为address_id的外键列,
//该外键列参照当前实体的关联实体对应表的主键列
inverseJoinColumns = @JoinColumn(name = "address_id", //
referencedColumnName = "address_id" )
)
private Set<Address> addresses = new HashSet<Address>();

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Set<Address> getAddresses() {
return addresses;
}

public void setAddresses(Set<Address> addresses) {
this.addresses = addresses;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

}

Address.java

package org.crazyit.app.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Table(name = "Address_inf")
public class Address {

@Id
@Column(name = "address_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

// 地址详细
private String addressDetail;

// 无参构造方法
public Address() {
}

// 初始化全部成员变量
public Address(String addressDetail) {
this.addressDetail = addressDetail;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getAddressDetail() {
return addressDetail;
}

public void setAddressDetail(String addressDetail) {
this.addressDetail = addressDetail;
}

}

#数据模型

注解:【有连接表的】Hibernate单向N->N关联

上一篇:linux 信号signal和sigaction理解


下一篇:[LeetCode] K-diff Pairs in an Array 数组中差为K的数对