hibernate annotation one-to-many

hibernate一對多,多的一方建立外鍵,例:

CREATE TABLE `person` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `personName` varchar(45) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;


 

CREATE TABLE `house` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `houseNo` varchar(45) NOT NULL,
  `person_id` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `FK42AD7008BA56E9D` (`person_id`),
  CONSTRAINT `FK42AD7008BA56E9D` FOREIGN KEY (`person_id`) REFERENCES `person` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;


 

import java.io.Serializable;
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.OneToMany;
import javax.persistence.Table;


@Entity
@Table
public class Person implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = -6396702070077903027L;

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	public Long getId() {return id;}
	public void setId(Long id) {this.id = id;}
	private Long id;
	
	@Column(length=45,nullable=false)
	public String getPersonName() {return personName;}
	public void setPersonName(String personName) {this.personName = personName;}
	private String personName;
	
	
	@OneToMany(mappedBy="person",cascade=CascadeType.ALL)
	public Set<House> getHouseSet() {return houseSet;}
	public void setHouseSet(Set<House> houseSet) {this.houseSet = houseSet;}
	private Set<House> houseSet;
	
	

}

import java.io.Serializable;

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.ManyToOne;
import javax.persistence.Table;

@Entity
@Table
public class House implements Serializable{
	
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -2630598805462422037L;

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	public Long getId() {return id;}
	public void setId(Long id) {this.id = id;}
	private Long id;
	
	@Column(length=45,nullable=false)
	public String getHouseNo() {return houseNo;}
	public void setHouseNo(String houseNo) {this.houseNo = houseNo;}
	private String houseNo;
	
	@ManyToOne(cascade=CascadeType.ALL)
	@JoinColumn
	public Person getPerson() {return person;}
	public void setPerson(Person person) {this.person = person;}
	private Person person;

	
	
	
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章