简体   繁体   中英

JPA mapping for one to many with inheritance mapping

I have one scenario.

@Entity
@Table(name = "someTable")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Access(AccessType.FIELD)
@DiscriminatorColumn(name = "someDisc")
public abstract class AbstractClass{}

and

@Entity
@Access(AccessType.FIELD)
@DiscriminatorValue("1")
public class Child1 extends AbstractClass{
}

@Entity
@Access(AccessType.FIELD)
@DiscriminatorValue("2")
public class Child2 extends AbstractClass{
}

Now in 3rd table I want something like this

@Entity
@Table
public class ThridTable{

    @OneToMany(cascade = CascadeType.ALL, fetch = EAGER, orphanRemoval = true)
    @JoinColumn(name = "foreinKeyCol", nullable = false)
    @OrderColumn(name = "orderCol")
    private List<Child2> child2 = new ArrayList<>();


    @OneToMany(cascade = CascadeType.ALL, fetch = EAGER, orphanRemoval = true)
    @JoinColumn(name = "foreinKeyCol", nullable = false)
    @OrderColumn(name = "orderCol")
    private List<Child1> child1 = new ArrayList<>();

//more setters/getters
}

now while it persists well and values are getting saved correctly in the table. The problem I face while fetching object using ThridTable object. The generated query doesn't ditinguish between two instances ie child1 and child2 in same table and tries to update object of child2 in child one.

if you're using hibernate you can add a @Where condition to the @OneToMany Mappings.

Eg:

@OneToMany(cascade = CascadeType.ALL, fetch = EAGER, orphanRemoval = true)
@JoinColumn(name = "foreinKeyCol", nullable = false)
@OrderColumn(name = "orderCol")
@Where(clause="someDisc=1")
private List<Child1> child1 = new ArrayList<>();

have a look at the api: http://docs.jboss.org/hibernate/core/4.1/javadocs/org/hibernate/annotations/Where.html

and: http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-hibspec-collection

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