nivis
nivis

Reputation: 933

Multiple instances of generic class

I'm trying to create a generic DAO in order to avoid having more or less the same code in many separate DAOs.

My problem is that in the following lines of code:

private BaseDAOImpl<Artist> baseDAOArtist = new BaseDAOImpl<>(Artist.class);
private BaseDAOImpl<ArtistRelation> baseDAOArtistRelation = new BaseDAOImpl<>(ArtistRelation.class);

The first one seems to be skipped.

An excerpt of the BaseDAOImpl:

public class BaseDAOImpl<T> implements BaseDAO<T> {

    private Class<T> entity;
    private DAOFactory daoFactory = Config.getInstance().getDAOFactory();
    private static String SQL_FIND_BY_ID;

    public BaseDAOImpl(Class entity) {
        this.entity = entity;
        SQL_FIND_BY_ID = "SELECT * FROM VIEW_" + entity.getSimpleName() + " WHERE id = ?";        
    }
}

Is it not possible to instantiate multiple objects this way?

Upvotes: 0

Views: 174

Answers (2)

Pyranja
Pyranja

Reputation: 3599

Without a more detailed description of the error I am more or less guessing now, but judging from variable names and the code snippet I would suspect the static field SQL_FIND_BY_ID to be the cause.

When you instantiate the two DAOs, the second execution of the constructor BaseDAOImpl will overwrite the value of the static field. If the DAO relies on the SQL query stored there, it will always query for the entity of the last instantiated DAO.

Static fields and methods are shared among all instances of a class even if they differ on their generic parameters. In contrast to e.g. C++'s templates, there are no separate classes generated for each generic parameter.

To achieve the desired behavior of separate queries for each entity you may change the static field to a non-static member.

Upvotes: 0

Chris B
Chris B

Reputation: 925

Yes. It's not clear what you mean by "The first one seems to be skipped." but it could be that your using a static value for "SQL_FIND_BY_ID"? As at the moment:

private BaseDAOImpl<Artist> baseDAOArtist = new BaseDAOImpl<>(Artist.class);

Creates two instance variables and sets the value of SQL_FIND_BY_ID then:

private BaseDAOImpl<ArtistRelation> baseDAOArtistRelation = new BaseDAOImpl<>(ArtistRelation.class);

Creates two new instance variables and will change the value "SQL_FIND_BY_ID" for both instances.

Upvotes: 1

Related Questions