Anand
Anand

Reputation: 707

Multiple Inheritance in Java - Spring Data

I want to create a DAO class named BaseDAO that should have the JPA and JDBC capabilities in Spring. I mean, I want to extend JPADAOSupport and JDBCDAOSupport classes of spring in to my BaseDAO class. I am aware that multiple inheritance is not an option in Java.

I have created two separate Base classes like BaseJPADao and BaseJdbcDao extending the respective classes. Is it possible to have a single class to extend both? Is there any design pattern solving this issue. Please advise.

Upvotes: 0

Views: 1778

Answers (3)

Christian Bongiorno
Christian Bongiorno

Reputation: 5648

This would be easy to do with delegation if they both had interface level access you want:

public class MyUberClass implements WhateverJPADAOSupportDoes, WhateverJDBCDAOSupportDoes {
    private JPADAOSuport jpa;
    private JDBCDAOSupport jdbc;

    // now implement all methods specified by the interfaces on the class signature and delegate to their respective member
}

But it seems you want access to all of their public methods. As there is no interface for both you can do the same as above but it can't be of both types simultaneously. The language expressly denies you this.

Your only other option is to create an adapter interface that your code can rely on and then use the combination delegation. If you're hoping to have one class that you can just drop in as a substitution for both then the answer is you can't.

Upvotes: 0

Vlad Mihalcea
Vlad Mihalcea

Reputation: 154090

Why don't you have a DaoGateway bean having injected the actual JPA DAO and the JDBC DAO beans.

This gateway can then decide which DAO to delegate a given request (to JPA or to JDBC).

You should always favour composition vs inheritance when reusing functionalities.

Upvotes: 2

Stultuske
Stultuske

Reputation: 9437

no it is not. if it was possible, you would still have the same result as in one class extending JPADAOSupport and JDBCDAOSupport, which you yourself say you know is not possible because multiple inheritance is impossible.

you can write to an interface, and provide two implementations, though.

Upvotes: 0

Related Questions