hibernate学习(设计多对多 关系 映射)

//
package org.crazy.app.domain;
import java.util.HashSet;
import java.util.Set; import javax.persistence.*;
@Entity
@Table(name="person_inf")
public class Person {
@Id
@Column(name="person_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
private String name;
private int age;
@ManyToMany(targetEntity=Address.class)
@JoinTable(name="person_address",
joinColumns=@JoinColumn(name="person_id",referencedColumnName="person_id"),
inverseJoinColumns=@JoinColumn(name="address_id",referencedColumnName="address_id"))
private Set<Address> address=new HashSet<Address>(); public Person() { }
public Person(String name, int age) {
this.name = name;
this.age = age;
}
//
public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Set<Address> getAddress() {
return address;
}
public void setAddress(Set<Address> address) {
this.address = address;
} }
//**************************************
package org.crazy.app.domain; import java.util.HashSet;
import java.util.Set; import javax.persistence.*; @Entity
@Table(name="address_inf")
public class Address {
@Id
@Column(name="address_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer addressId;
private String addressDetail;
@ManyToMany(targetEntity=Person.class)
@JoinTable(name="person_address",
joinColumns=@JoinColumn(name="address_id",referencedColumnName="address_id"),
inverseJoinColumns=@JoinColumn(name="person_id",referencedColumnName="person_id"))
private Set<Person> persons=new HashSet<Person>();
public String getAddressDetail() {
return addressDetail;
}
public void setAddressDetail(String addressDetail) {
this.addressDetail = addressDetail;
}
public Set<Person> getPersons() {
return persons;
}
public void setPersons(Set<Person> persons) {
this.persons = persons;
}
public Address(String addressDetail) {
this.addressDetail = addressDetail;
}
public Address() { } }

2,测试

        Person p = new Person();
// 设置Person的name为crazyit
p.setName("crazyit");
p.setAge(20);
// 持久化Person对象(对应于插入主表记录)
session.save(p);
// 创建一个瞬态的Address对象
Address a = new Address("广州天河");
// 先设置Person和Address之间的关联关系
a.getPersons().add(p);
// 再持久化Address对象
session.persist(a);
// 创建一个瞬态的Address对象
Address a2 = new Address("上海虹口");
// 先设置Person和Address之间的关联关系
a2.getPersons().add(p);
// 再持久化Address对象(对应于插入从表记录)
session.persist(a2); Person p2 = new Person();
p2.setName("fkit");
p2.setAge(29);
p2.getAddress().add(a2);
session.save(p2);

hibernate学习(设计多对多 关系 映射)

上一篇:mysql substring_index


下一篇:Looksery Cup 2015 A. Face Detection 水题