2022年12月29日 星期四

[Spring Boot] 實作書中範例系列文2 - 一個人有多個手機,一個手機只屬於一人

 


1. 新增Phone與修改Person

至此步驟code


package com.example.demo;

import lombok.Data;

import javax.persistence.*;

@Entity
@Table(name="T_PHONE")
@Data
public class Phone {
    private Long id;
    private String number;
    private Person person;
    @Id
    @GeneratedValue (strategy = GenerationType.TABLE, generator = "MY_TABLE_GENERATOR")
    @TableGenerator (name = "MY_TABLE_GENERATOR",
            table="T SEQUENCES",
            pkColumnName = "SEQ_NAME",
            valueColumnName = "SEO_VALUE",
            pkColumnValue = "PHONE")
    @Column (name = "ID")
    public Long getId() {
        return id;
    }
    @Column (name = "NUMBER")
    public String getNumber () {
        return number;
    }
    @ManyToOne
    @JoinColumn (name = "PERSON_ID")
    public Person getPerson () {
        return person;
    }
}
package com.example.demo;
import javax.persistence.*;
import java.util.*;


@Entity
@Table (name = "T_PERSON")
@Inheritance (strategy = InheritanceType.SINGLE_TABLE)
public class Person {
    ...
    @OneToMany (mappedBy = "person")
    private List<Phone> phones = new ArrayList<Phone>();
    public List<Phone> getPhones () {
        return phones;
    }
}
Hibernate: 
    
    create table t_phone (
       id int8 not null,
        number varchar(255),
        person_id int8,
        primary key (id)
    )
Hibernate: 
    
    alter table t_phone 
       add constraint FKgtes359540rlr1bxkiq2t244h 
       foreign key (person_id) 
       references t_person

沒有留言:

張貼留言