-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: How to dynamically join an entity by its type
PostPosted: Sat Jun 25, 2016 6:28 am 
Newbie

Joined: Sat Jun 25, 2016 6:14 am
Posts: 1
Hello,

I have three tables, for instance user (id, name), category (id, name) and entity_category (entity_id, entity_type, category_id). How to do join them in annotation to get Category JPA object in User JPA (I need join by constant entity_type and user id) and have possibility to save relations to entity_category table when I save User JPA?
Code:
@OneToOne
    @JoinTable(name = "entity_category",
        joinColumns = {
            @JoinColumn(name = "entity_id", referencedColumnName="id")
        },
        inverseJoinColumns = {
                @JoinColumn(name = "category_id")
        })
    @WhereJoinTable(clause = "entity_type = 1")

Code works, but entity_type isn't saved when I save user JPA object.
If possible to solve it using Hibernate 4?


Top
 Profile  
 
 Post subject: Re: join table by constant and id
PostPosted: Sat Jun 25, 2016 9:40 am 
Hibernate Team
Hibernate Team

Joined: Thu Sep 11, 2014 2:50 am
Posts: 1638
Location: Romania
Yes, you can! But not with JPA, with the Hibernate @Any annotation.

Your mapping will become something like this:

Code:
@AnyMetaDef( name= "EntityMetaDef", metaType = "int", idType = "long",
    metaValues = {
        @MetaValue(value = "1", targetEntity = Category.class)
    }
)
@Any(
    metaDef = "EntityMetaDef",
    metaColumn = @Column( name = "entity_type" )
)
@JoinColumn( name = "entity_id" )
private Category category;

_________________
If you liked my answer, you are going to love my High-Performance Java Persistence book and my blog as well.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.