Shreyas Nargund
Shreyas Nargund

Reputation: 145

How to save a sub-entity of an entity using spring-data

I am trying to do an assignment using Spring Boot and spring-data. I have 2 entities Organization and Location.

1.Organization

public class Organization {
    private Long id;
    private String name;
    private Location location;
}

public class Location {
    private Double lattitude;
    private Double longitude;
}

And my database table is like:

CREATE TABLE organization (
    id int primary key,
    organization_name varchar(255),
    organization_location_lat double,
    organization_location_long double
)

Now I am using spring data to persist this entity in database.In normal scenario just invoking the save(Organization org) method would persist the data but I am not sure how to store the organization data with the location. Can someone help me with this?

Upvotes: 2

Views: 2605

Answers (1)

xyz
xyz

Reputation: 5407

Entities have an identity . Embeddables have no identity of their own and can only be queried for using the owning entities.

you Organization is @Entity lication should be @Embeddable(as there is no id , and it's part of Organization table).

But , I think it's not your case according to your table ,if Location is just part a of Organization and doen't have own lifecycle (exists only inside Organization) . If Location has lifecycle outside the Organization it should be entity (then should be id for Location as for entity) and you need relationship between Organization and Location , dependence on case how you use is , like one-to-one or many to one and use sascade type for location

public class Organization {
    @Id
    private Long id;
    @Column
    private String name;
    @Embedded
    private Location location;
}

@Embeddable
public class Location {
    private Double lattitude;
    private Double longitude;
}

see example https://docs.jboss.org/hibernate/orm/5.1/userguide/html_single/chapters/domain/embeddables.html

Upvotes: 2

Related Questions