Spring Data REST convert/show EmbeddedId including ManyToOne

762 views Asked by At

I have a question for my project in Spring Data REST.

My model includes two tables with EmbeddedIds. The first table (name=B) consist of two integers. The second table (name=A) consist of a simple FK and the model of B (includes the EmbeddedId).

Now, if I make a request for table B, I'll get the two IDs. However, if I make a request for table A, I wont get the IDs..

So I overrid the toString()-method in my EmbeddedId-class, to return at least the IDs right in the URI-link.

I read about BackendIdConverter or Spring core.converter and tried to convert the IDs right, but I wasn't able to reach my goal (got errors). So now, I need your help!

To fully understand my problem, here's my structure (as demo):

@Embeddable
public class IDsFromA implements Serializable {

    @ManyToOne
    @JoinColumn(name="cID")
    private C c;

    @ManyToOne
    @JoinColumns({
        @JoinColumn(name="b_1", referencedColumnName="b_1"),
        @JoinColumn(name="b_2", referencedColumnName="b_2")
    })
    private B b;
}

@Embeddable
public class IDsFromB implements Serializable {

    private int b_1;
    private int b_2;
}

@Entity
public class A {

    @EmbeddedId
    private IDsFromA idsFromA;

    // ...
}

@Entity
public class B {

    @EmbeddedId
    private IDsFromA idsFromA;

    // ...
}

@Entity
public class c {

    @Id
    private int cID;

    // ...
}
1

There are 1 answers

3
Alan Hay On

The Jackson JSON serializer will by default also serialize any public get..() methods. So you can simply add a couple of methods to return the relevant data and the values should be in the response:

e.g.

@Entity
public class A {

    @EmbeddedId
    private IDsFromA idsFromA;

    public int getValueOne(){
        return idsFromA.getB().getIdsFromB().getB_1();
    }

     public int getValueTwo(){
        return idsFromA.getB().getIdsFromB().getB_2();
    }
}