1

I have an interface IExample, for my class Example, which is a Hibernate entity, because I want my app to allow other devs to change the implementation of my model layer. My interface is as follows:

public interface IExample {

    public int getId ();
    public void setId (int id);

    public IOtherClass getOtherClass ();
    public void setOtherClass (IOtherClass otherClass);

}

IOtherClass is the interface for another Hibernate entity OtherClass.

My class is:

@Entity
@Table(name="example")
public class Example implements IExample {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @OneToOne(targetEntity=OtherClass.class)
    @JoinColumn(name="otherclass")
    private IOtherClass otherClass;

}

As you can see, I'm using the interface IOtherClass and mapping it to a Hibernate entity with

targetEntity=OtherClass.class

This works fine, but the problem comes when I try to use DAOs. As I'm working with IOtherClass in my Example, I would like to be able to tell my hibernate that when I call:

Example example = new Example();
IOtherClass otherClass = example.getOtherClass(); // Returns IOtherClass
getCurrentSession().save(otherClass);

I'm not trying to save the interface but my OtherClass entity. If I try to do this, actually, I get the exception:

Unable to locate persister: IOtherClass

One option would be to explicitly cast every IOtherClass entity my DAO gets to OtherClass, but that is unsafe, and doesn't look like the best way to code this.

My question is: Is there a way (through annotations or something like that) to tell my DAOs what class to look for when they receive an instance of IOtherClass?

David Antelo
  • 503
  • 6
  • 19
  • Just tried and doesn't work. Apparently you can't use it with interfaces https://stackoverflow.com/questions/49045027/can-i-use-mappedsuperclass-annotation-on-an-interface. – David Antelo Jul 07 '19 at 09:49
  • Are you sure that example.getOtherClass() is not null and an instance of OtherClass? Session.save doesn't care about the compile-time type of its parameter. – Piotr P. Karwasz Jul 07 '19 at 19:20
  • Yes, I have checked. My final solution to this problem was actually creating an abstract method in my abstract parent class that casts the interface to the actual class, and now it works, so there's no way I wasn't actually returning the right object. Thanks for the answer – David Antelo Jul 07 '19 at 22:03
  • I wasn't able to reproduce the problem with Hibernate 5.4, so I am guessing. If I put the concrete classes in Hibernate's config file everything works just fine. – Piotr P. Karwasz Jul 08 '19 at 18:33

0 Answers0