Java – spring data rest adds inheritance issues

I have a spring database on a JPA entity The entity is subclassed through connection inheritance

At least automatically, spring data rest seems to have a problem explaining this structure Or maybe I misunderstood inheritance Usage of joined

The request of any entity with an event will return the following:

{
    cause: null,message: "Cannot create self link for class com.foo.event.SubEvent! No persistent entity found!"
}

Maybe I asked the project too much about how to deal with this problem, but is there a solution to group all events under the same event? Maybe even allow me to filter types?

I have left the basics of the application structure below

Event. java

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@JsonTypeInfo(use = Id.NAME,include = As.PROPERTY,property = "type")
@JsonSubTypes({
  @Type(value = SubEvent.class),...
})
...
public class Event {
    @Id
    private long id;
    ...
}

SubEvent. java

@Entity
public class SubEvent extends Event {
    private String code;
    ...
}

EventRepository. java

@RepositoryRestResource(path = "events")
public interface EventRepository extends PagingAndSortingRepository<Event,Long> {
    ...    
}

Solution

I don't think you used discriminator to let JPA know what subclasses a given object uses (how does it know?)

I prefer to use abstract classes to represent the hierachies of each subclass, so here is an example suitable for you:

Event. java

@Entity
@DiscriminatorColumn(name = "type")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Event {
    @Id
    @GeneratedValue
    public Long id;

    public String type;
}

SubEvent. java

@Entity
@DiscriminatorValue("subevent")
@PrimaryKeyJoinColumn(name = "event_id")
public class PeeringService extends Service {
    private String code;
}

Using the above code, you will notice some strange things - when generating the resource path of one of these objects, it assumes that you have a repository for each subclass, and generates the following:

{
  "type" : "subevent","code" : "bacon","_links" : {
    "self" : {
      "href" : "http://localhost:8081/subEvents/1"
    },"peeringService" : {
      "href" : "http://localhost:8081/subEvents/1"
    }
  }
}

This is easy to solve, but you only need to add the following comments to your base class:

@RestResource(path = "events")

It will generate the resource path you expect!

I hope this helps:)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>