JPA的映射

下面总结一下jpa的映射:

这些映射可以都配置成双向关联,然后设置维护端,多对一 维护端要设在多的一段

其他根据情况设定。设置维护端要在被维护端设置(mappedBy)见下面代码

一对一:oneToone

一对多/多对一:manytoone

多对多:manytomany:

 

下面是各种类型的属性的映射方法:one-one 映射,配置成了双向关联,维护方为person
package cn.itcast.bean;

import java.util.Date;

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.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
public class IDCard {
	private Integer cardid;
	private String cardno;
	private Date birthday = new Date();
	private Person person;
	public IDCard(){}
	
	public IDCard(String cardno) {
		this.cardno = cardno;
	}	
//解释:mappedBy 维护方为person类里的card属性 ,cascade为级联 这里是级联刷新,
	@OneToOne(mappedBy="card",cascade=CascadeType.REFRESH)
	public Person getPerson() {
		return person;
	}
	public void setPerson(Person person) {
		this.person = person;
	}
	@Id @GeneratedValue(strategy=GenerationType.IDENTITY)//Id 表示这里为主键 GeneratedValue配置主键生成策略
	public Integer getCardid() {
		return cardid;
	}
	public void setCardid(Integer cardid) {
		this.cardid = cardid;
	}
	
	@Column(length=18,nullable=false)
	public String getCardno() {
		return cardno;
	}
	public void setCardno(String cardno) {
		this.cardno = cardno;
	}
	
	@Temporal(TemporalType.DATE) @Column(nullable=false) //日期类型的 nullable 是否可以为空
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	
}

 

package cn.itcast.bean;

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.OneToOne;

@Entity
public class Person {
	private Integer id;
	private String name;
	private IDCard card;
	
	@OneToOne(cascade=CascadeType.ALL,optional=false) //optional为false 则card不为null
	@JoinColumn(name="card_id") // 设置外键的名称,不设置会使用jpa自动生成的。
	public IDCard getCard() {
		return card;
	}
	public void setCard(IDCard card) {
		this.card = card;
	}
	@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	@Column(length=10,nullable=false)
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}

 

你可能感兴趣的:(bean,jpa)