简体   繁体   中英

Spring JPA: no property id found for Object with `@Any` annotation

I wish to create an Attachment entity that may be related to entities of different types, so I am trying to use @Any annotation for that. My code is like this:

@Entity
public class Attachment{
    @XmlElement
    @Any(metaColumn = @Column(name = "containerType"), fetch = FetchType.LAZY)
    @AnyMetaDef(idType = "long", metaType = "string",
        metaValues = {
            @MetaValue(targetEntity = TestApp.class, value = "TestApp")
    })
    @JoinColumn(name = "container_id")
    private Object container;

    @XmlElement
    @Column(insertable = false, updatable = false) //this I added cause Hibernate said so
    private String containerType;
}

My problem now is that when I start my app, DB initialization fails with:
org.springframework.data.mapping.PropertyReferenceException: No property id found for type Object! Traversed path: Attachment.container

All the examples of using @Any I've found so far are exactly the same. So what is the right way of doing this?

The error says the for field: @JoinColumn(name = "container_id") private Object container;

You use JoinColumn , but JPA can not find the ID field in Object . The meaning is, when you use JoinColumn , JPA needs to know the column name in current table, Attachment in this case, and the referenced column in the joined table, that is container .

But as you said, you want to let this table related to entities of different types. I think you can not do that. In my understanding, JPA is a little like 'static' explanatory. You can not make it 'dynamic'.

So far I've managed to overcome this by providing an IAttachable interface with getId() method and replacing Object with IAttachable in my relation definition.

Not sure if this is the best way, but it works so far.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM