Mapping collection inside container entity to one table


#1

I have the following class structure:

public class Container {

    private Set<Child> childs  = new HashSet<>();
}

public class Child {
    String name;
    String value;
    String param;
}

Because of Container class is going to be single in application (just wrapper on collections that may be updated), I would like to store it in one table, e.g.“childs” with columns

id | name | value | param
Is it possible to make such mapping in order to use Container when fetch or store it through hb session with corresponding updates to childs collection:

getSession().saveOrUpdate(container)
And if so, what mapping should be in that case?


#2

The Container entity is the parent.

That means the Child needs to have a FK back to its Parent.

So, the Container entity needs to be backed by a container table so that its PK is referenced by the Child table FK.

That’s how a one-to-many table relationship works.

For more details bout how to map this association, check out this article.


#3

Thanks for the reply!
I am still confused is it possible to map using one table. If we have ids fields in table. So container_id will always the same and child_id will be different and that’s what pk would be

container_id | child_id | name | value | param


#4

So, if there is no container table, is that value coming from some external system?

You cannot map an entity without having a table. Theoretically, you could map the Container entity to a View using an SQL query like this one:

CREATE OR REPLACE VIEW container_view AS 
select distinct container_id as id
from child

and the Container entity becomes:

@Entity
@Table(name = "container_view ")  
public class Container{
 
    @Id
    @Column(name = "id")
    private Long id; 
}