Hibernate关联映射

单向关联关系

单向1->1

和单向N->1配置唯一不一样的地方是在many-to-one的标签上加上unique=“true”,即可完成1->1的映射




	
		
		
			
			
		
		
		
		
	



单向1->N

public class Person
{
	private int id;
	private String name;
	private int age;
	private Set
addresss=new HashSet
(); public Person(){} public int getId() { return id; } public void setId(int id) { this.id = id; } 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
getAddresss() { return addresss; } public void setAddresss(Set
addresss) { this.addresss = addresss; } }




	
		
		
			
			
		
		
		
		
			
			
		
	

Address类和之前的一样,要注意的是一对多关系,会先对主表进行操作在对从表进行操作,比如插入一条sql,会先对主表插入数据,这时候主表的id还为确定,会在之后根据从表信息更新主表,所以不效率建议使用双向一对多关系。


	public void singleOneToMany(){
		Session session=HibernateUtil.currentSession();
		tx=session.beginTransaction();
		Person p=new Person();
		Address a=new Address();
		a.setAddressDetail("上海");
		Address b=new Address();
		b.setAddressDetail("北京");
		session.persist(a);
		session.persist(b);
		p.setName("czk");
		p.setAge(23);
		p.getAddresss().add(a);
		p.getAddresss().add(b);
		session.save(p);
		tx.commit();
		HibernateUtil.closeSession();
	}



单向N->1

public class Person
{
	private int id;
	private String name;
	private int age;
	private Address address;
	public Person(){}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	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 Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age
				+ ", address=" + address.getAddressDetail() + "]";
	}
}


	
		
		
			
			
		
		
		
		
	

many-to-one的cascade属性设置为all 是为了设置增删查改的级联关系,每次操作从表都先对主表做操作

public class Address {
	private int adressId;
	private String addressDetail;
	public Address(){}

	public int getAdressId() {
		return adressId;
	}

	public void setAdressId(int adressId) {
		this.adressId = adressId;
	}

	public String getAddressDetail() {
		return addressDetail;
	}

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


	
		
			
		
		
			
		
	

person_inf表


address_inf表




单向N->N



你可能感兴趣的:(ssh)