0

I have this "Parent" class :

@Entity
@Table(name = "parent_table")
public class Parent {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String firstName;
    private String lastName;

    @OneToMany(fetch=FetchType.LAZY, mappedBy = "parent", cascade = {CascadeType.ALL})
    List<Child> children;
 }

And, I have the following child class :

@Entity
@Table(name = "children")
public class Child {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long childId;

    @ManyToOne
    @JoinColumn(name="parent_id")
    private Parent parent;

    private String name;
}

I am also sending this as my request body :

{
        "firstName": "Test",
        "lastName": "Parent",
        "children":[{
                "name":"jack"
            },
            {
                "name":"jill"
            }
        ]

}

The good news is that is that I can write these children to the database directly from the parent repository, however... when I do my GET, to get a parent, it comes back without the child entities (even though they are in the database, in their table)

SEMI-USEFUL UPDATE (MAYBE?) : I have noticed that the parent_id field in the database for the child records doesn't seem to be getting populated! No idea why!

Slippy
  • 1,253
  • 5
  • 22
  • 43
  • All ok. `fetch=FetchType.LAZY` Try call parent.getChildren().size() – Crutch Master Mar 07 '19 at 03:42
  • @CrutchMaster - when I use laze (or eager, for that matter) I definitely get zero back... and my parent item comes back correctly, but it contains an empty json array in the response for the children section :( – Slippy Mar 07 '19 at 03:56
  • You should enable the SQL log, this might give you some hints what's wrong: https://stackoverflow.com/questions/1710476/how-to-print-a-query-string-with-parameter-values-when-using-hibernate – Svetlin Zarev Mar 07 '19 at 04:59
  • When you debug, does your repository return the children? If so, then problem is Jackson. Please confirm repo works fine with EAGER settings – Cristian Colorado Mar 07 '19 at 05:11
  • Also, your parent id and @JoinColumn must be the same. You have id and parent_id – Cristian Colorado Mar 07 '19 at 05:13

1 Answers1

0

You are creating the relationship with the wrong column names.

Your parent class has id column defined as:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

That will generate a column id in your parent table.

Your child class has foreign key defined as:

 @ManyToOne
 @JoinColumn(name="parent_id")
 private Parent parent;

You indicate to look for parent_id column within parent table to make a relationship. Such column does not exist.

If you wish to indicate foreign key column name must be parent_id you have to define it as:

 @ManyToOne
 @Column(name = "parent_id") // Your child field
 @JoinColumn(name="id") // Your parent id field
 private Parent parent;
Cristian Colorado
  • 2,022
  • 3
  • 19
  • 24