从Hibernate 2.5开始就可以使用annotation实现实体关系的映射了,减少了配置hbm文件的繁琐,而且annotation也是一种趋势,现在的SSH2的整合都是完全可以用annotation来实现。在以前实现一对多关联的关联式都是使用hbm文件,今天我们来使用annotation试试,同样也能实现其功能。 1.数据库:oracle数据库,有person和address二张表,一对多的关系。 create table person
数据库 2.Person实体类: package com.zengguo.po; import java.io.Serializable; 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.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; @SuppressWarnings(“serial”) @Entity @Table(name = “person”) public class Person implements Serializable { //oracle 序列 @Id @GenericGenerator(name = “personGenericGenerator”, strategy = “sequence”, parameters = { @Parameter(value = “hibernate_seq”, name = “sequence”) }) @GeneratedValue(generator=”personGenericGenerator”) private long id; @Column(name=”uname”) private String uname; @OneToMany(targetEntity=Address.class,cascade=CascadeType.ALL) @Fetch(FetchMode.JOIN) //updatable=false很关键,如果没有它,在级联删除的时候就会报错(反转的问题) @JoinColumn(name=”personId”,updatable=false) private Set<Address> sets = new HashSet<Address>(); public Set<Address> getSets() { return sets; } public void setSets(Set<Address> sets) { this.sets = sets; } public Person() { super(); } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } } 3.Address实体类 package com.zengguo.po; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; @SuppressWarnings(“serial”) @Entity @Table(name = “address”) public class Address implements java.io.Serializable { //使用序列生成主键 @Id @GenericGenerator(name = “addressGenericGenerator”, strategy = “sequence”, parameters = { @Parameter(value = “hibernate_seq”, name = “sequence”) }) @GeneratedValue(generator = “addressGenericGenerator”) private long id; @Column(name = “address”) private String address; //多对一,@JoinColumn与@column类似,指定映射的数据库字段 @ManyToOne(targetEntity = Person.class) @JoinColumn(name=”personId”,updatable=false) private Person person; public Address() { super(); } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } } |