lundi 26 juin 2017

Java Play, Getting Database Connection outside of a controller

For a work project I am attempting to create a Query class that connects to the database. It used to be done like so:

Connection dbC = DB.getConnection(); 

However, that's now deprecated so I am using the recommended method as described in Play docs:

@Inject private play.db.Database db;

public AQuery(Database db)
{
    this.db = db;
}

I also have a method to get a List of objects.

public List<GenObject> getObjectID(int iD)
{
    List<GenObject> events = new LinkedList<>();
    Connection dbC = null;
    ResultSet rs = null;
    PreparedStatement ps = null;
 //Continues...
}

The idea here is that in this method, to get the connection I call

dbC = db.getConnection();

That's all fine until I get to my controller. I cannot call getObjectID because it is not static. Great, I thought, so I'll just create an AQuery object and use that. But that's not possible without passing a Database object to the constructor, which I don't have. How would you create an instance of the AQuery object (or avoid that altogether and make the db field static) so that I can use my getObjectID method?




Aucun commentaire:

Enregistrer un commentaire