JPA 使用@OneToOne

OneToOne,就是一对一映射,现实生活中比较常见的例子就是一个人有一个身份证,一个丈夫只能有一个老婆

新建一个Person和Address类

@Entity
@Table(name="s_person")
public class Person {
	
	@GeneratedValue(generator = "uuid2")
        @GenericGenerator(name = "uuid2", strategy = "uuid2")
	@Id
	private String id;
	private String username;
	private String age;
	private String addressId;
	
	@OneToOne
	@JoinColumn(name="addressId",referencedColumnName="id")
	private Address address;
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
	public String getAddressId() {
		return addressId;
	}
	public void setAddressId(String addressId) {
		this.addressId = addressId;
	}

}

@joincolumn 中name的属性对用数据库中的字段addressId,referencedColumn Name属性对应关联表的主键

Address.java

@Entity
@Table(name="s_address")
public class Address {
	private String id;
	private String address;
	private String name;
	
	@GeneratedValue(generator = "uuid2")
        @GenericGenerator(name = "uuid2", strategy = "uuid2")
	@Id
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

接口

public interface PersonRepository extends JpaRepository{

	Person findById(String id);

}

数据库



JPA 使用@OneToOne_第1张图片

输出


你可能感兴趣的:(JPA)