Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JPA (Hibernate) auto-flatten nested objects into single table

I used to know how to do this but for the life of me can't even remember what to google for! I have a bunch of POJOs with a handful of simple fields (primitives, Strings, etc) each, and I want to just add them all into a parent POJO and store the whole lot together as a single row in a single table (without having to duplicate and copy every field from the child POJOs into the parent POJO). I believe there is an annotation, or perhaps a Hibernate converter, that I can use to do this very easily?

As an example, say I have:

class A {
  Integer foo;
  String bar;
}
class B {
  Integer lol;
  String rofl;
}

I want a parent object like:

@Entity
class P {
  A a;
  B b;
}

Which will have a database schema of foo,bar,lol,rofl

Any help much appreciated!

like image 342
Matt Avatar asked Aug 23 '17 11:08

Matt


1 Answers

I think you have 2 Classes, having some common attributes. So you want to create another common class that should be used with those classes but will not be mapped to any specific table in database(I mean this common class will have existence/will be handled just on application level). Like Consider 2 class Student & Teacher, having some common attributes like name, gender etc. So now can push those common attributes in a common class like for example Human. So if that the case, than do something like this:

@Embeddable
public class Human{
    private String name;
    private String gender;

    //Constructors, getters & setters
}

Now Create a specific class like Student

public class Student{

    @Embedded
    private Human human;
    private String rollNo;
    //....
    //Constructors, getters & setters
}

and so for Teacher class.

Now you can save these entries like:

Human human = new Human();
human.setName("your-name");
//....

Student student = new Student();
student.setHuman(human);
student.setRollNo("343");
//....

and save it like

studentRepository.save(student);

So in database, just one record will be saved for Student(name, gender, rollNo ...). Because here in this case, Human is just the combination of parameters of Student and is not an entity.

like image 84
Afridi Avatar answered Nov 15 '22 05:11

Afridi