Java Tutorial/JPA/Embeddable

Материал из Java эксперт
Версия от 17:44, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Embeddable Entity

File: Student.java



import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Student {
    @Id private int id;
    private String name;
    @Embedded private Address address;
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }

    public Address getAddress() {
        return address;
    }
    
    public void setAddress(Address address) {
        this.address = address; 
    }
    public String toString() {
        return "Student id: " + getId() + " name: " + getName() +
               " with " + getAddress();
    }
}





Embedded Objects Multiple Tables

File: Address.java



import javax.persistence.Column;
import javax.persistence.Embeddable;
@Embeddable
public class Address {
    private String street; 
    private String city; 
    private String state;
    @Column(name="ZIP_CODE")
    private String zip;
    public String getStreet() {
        return street;
    }
    
    public void setStreet(String address) {
        this.street = address;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getState() {
        return state;
    }
    public void setState(String state) {
        this.state = state;
    }
    public String getZip() {
        return zip;
    }
    public void setZip(String zip) {
        this.zip = zip;
    }
    public String toString() {
        return "Address street: " + getStreet() +
               ", city: " + getCity() +
               ", state: " + getState() +
               ", zip: " + getZip();
    }
}





Share Embeddable Entity

File: Company.java



import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Company {
    @Id private String name;
    @Embedded
    private Address address;
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    public Address getAddress() {
        return address;
    }
    
    public void setAddress(Address address) {
        this.address = address; 
    }
    public String toString() {
        return "Company name: " + getName() +
               " at " + getAddress();
    }
}