I need to create a class that handles connection methods. But I read online different ways to implement this.There are
Singleton
static method
1) Singleton like this example:
public SingletonHome{
private static SingletomHome s=null;
private SingletonHome(){
}
public static SingletongHome getInstance(){
//return instance s
}
public Connection getConnection(){
//return connection;
}
}
2) Use static method
public class Example{
public static Connection getConnection(){
//return connection;
}
}
Who is the best solution in an enviroment that uses connection pool, I get connection from the connection pool and after I need to handles these.Anyone can help me?
These two ways are not designed to be switched.
Suppose you need to change to another implementation, with Example.getConnection() or SingletonHome.getInstance().getConnection() you are stuck.
Besides these classes are not straight testable either.
You should really introduce an interface that defines operations required for a connection management.
And if your environment allows that, you should favor dependency injection to define and inject your singleton over the classical singleton pattern : it provides a lower coupling for clients.
Note that reinventing the wheel is never a good idea either and is never free bugs : libraries that handle for you the database connection management/pooling exist : commons-dbcp, HikariCP and others... You could probably not do better than these.
Use Pooling mechanism instead of these ways
Related
I'm writing some methods to deal with database operations. Each method first gets a connection, do the operations, and close the connection at end.
I wonder if Spring AOP can help handling the connection acquiring and closing. Specifically I want something like:
#Aspect
#Component
public class ConnAspect {
#Around("#annotation(connHandle)")
public void handleConnection(ProceedingJoinPoint pjp, ConnHandle connHandle) throws Throwable {
Connection conn = datasource.getConnection();
pjp.proceed(); // can pjp get variable conn?
conn.close();
}
}
#Component
public class DbOperation {
#ConnHandle
public void operation1(...) {
... // do some operation with conn
}
...
}
Is it possible to do so? Or should I turn to other solutions? Thanks for any hints and answers.
No, this is not possible, and the suggestions in the comments are not going to help you. You cannot magically inject a non-existent method parameter or local variable into a method. Besides, what you are trying to do is anti AOP: not to encapsulate your cross-cutting concern in an aspect, but somehow bleed aspect context into your application, which ideally should be unaware of the aspect and work without it. You should rather describe what you want to achieve instead of being fixated on a specific (bad) design you have dreamed up to implement your idea.
Besides, there are simpler, reflective ways for a method to fetch its own annotations than to abuse AOP for that purpose.
Im creating a simple DBHelper for my postgre DB using a JDBC driver.
Im wondering what are the best practices?
For example, are methods like initConnection() closeConnection() or any other, should be static one? Like:
void foo{
DBHelper.initConnection();
// do some logic, maybe:
// Data someData = DBHelper.getSomeData();
DBHelper.closeConnection();
}
Or maybe better if i will create a DBHelper object and call method for object. Like:
void foo2{
DBHelper dbhelper = new DBHelper();
dbhelper.initConnection();
// do some logic, maybe:
// Data someData = dbhelper.getSomeData();
dbhelper.closeConnection();
}
Is it matter at all?
Do i need always check if connection is open before i will try to retrive some data? What if it is close? And always try to close it in finally block?
EDIT:
in answer to #Kayaman comment:
So my foo method like this?
void foo3{
Connection conn = DBHelper.getConnection();
// do some logic, maybe:
// Statement statement = conn.createStatement();
// some stmt work
conn.close() //do i need check if stmt is closed before?
}
That will make my DBHelper class usefull only to getting connection. There will be no logic inside? (like GetInterestingRecords() or GetRecordsWithId(30) ?
Have you thought about defining the connection properties in the server config file (if it is a web app) and have the session opened for the whole application lifecycle?
Before implementing DBHelper you should check if some java libraries may satisfy your needs. If you take a look at this there are listed some libraries that seem to fit your problem.
If you decide to go on with your own custom implementation I suggest to make DBHelper a normal class with no static methods for managing the connections; the main reason is that with static methods you cannot manage multiple (i.e. connections to different databases) db connections at the same time. If you are using a java 7 implementation in your onw library you could also implement tha AutoClosable inferface in order to better manage the resource you library is managing.
I have read about DAO from here and I find it really interesting but a few things are still missing me.
I would like to use the Interface to implement for two different data sources - one is a Socket connection, the other a Database connection.
For this I do the following:
public class databasePartDAOImplementation extends Database implements PartDAO {
//implementation
}
and the Database class has a constructor and some methods for managing this connection. How can I set up these classes, so I could instantiate one Database connection and then uses multiple DAOs all using this one connection?
I'm thinking of creating and instance of Database() and casting it into all the DAOs when needed, but I am not sure of any downfalls to this.
The Database class I use looks like this
public class Database
{
protected Connection connection;
public Database() throws ClassNotFoundException
{
Class.forName("org.sqlite.JDBC");
connection = null;
try
{
connection = DriverManager.getConnection("jdbc:sqlite:database.s3db");
}
catch(SQLException e)
{
System.err.println(e.getMessage());
}
}
public Connection getConnection() {
return connection;
}
}
tl;dr Would using this be a good idea of accessing the db?
Database db = new Database();
databasePartDAOImplementation dao = (databasePartDAOImplementation) db;
dao.getAllRecords();
You are partially correct regarding the point that the DAO should manage the connection with its data source to obtain and store data. But, as you have asked, how can we have all DAOs share the same connection? Let me shed some light by considering of the following strategies and then things will fall into place:
Automatically generating DAO code: Normally, there exists a relationship between your business objects, their DAOs and their underlying DB tables. Automatic code generation can take place using that relationship. In complex cases, you may use third party tools for code generation. May not be what you are looking for, but I just wanted to put it out there.
DAO Factory:
In a scenario where you are not dealing with different data sources (apparently this is not your scenario), you would create a single DAO factory class and use the Factory Method pattern to create the different DAOs used by your application. The DAO factory would be the class to manage the connection to the data source in this case.
In the scenario where you are dealing with different data sources (this is most likely your scenario), you would create an abstract DAO factory (this is the Abstract Factory pattern). Then, again, using the Factory Method pattern, your abstract DAO factory creates the concrete DAO factories for each of your specific data sources. Each concrete DAO factory would be responsible of two main tasks:
Creating a DAO for each kind of data access
Implementing a static method (e.g. createConnection) that takes care of creating a connection with its specific data source. You should consider connection pooling implementation and usage for that matter.
All the DAOs that are created by a concrete DAO factory would then be able to call that static method (createConnection) to obtain a connection to the specific data source. This connection would essentially be the same connection across all DAOs of the concrete DAO factory.
Ideas presented in this answer are based on the detailed article Core J2EE Patterns - Data Access Object.
I'm new to this and I want to understand when is it appropriate to use DI in Java. Suppose I need to ping different networks with different ping parameters:
The class PingParams:
public class PingParams {
int timeout;
int retries;
}
The class PingResult:
public class PingResult {
int ttl;
boolean available;
}
The class PingService:
public class PingService {
private PingParams pingParams;
#Inject
public PingService(PingParams pingParams) {
this.pingParams = pingParams;
}
public PingResult ping(String ip) {
// ping using timeout and retries from pingParams
return new PingResult();
}
}
The client:
public class Client {
#Inject
PingService pingService;
private List<PingResult> doPing() {
List<PingResult> ret = new ArrayList<>();
String[] ips = new String[] {"127.0.0.1","127.0.0.2"};
for (String ip : ips) {
PingResult pr = pingService.ping(ip);
ret.add(pr);
}
return ret;
}
public static void main(String[] args) {
List<PingResult> prs = new Client().doPing();
System.out.println(prs);
}
}
I have 2 injection points:
I inject PingParams in the constructor of PingService.
Is this correct? I mean, the DI container can not know the timeout and retries to inject into the PingParams unless you create some "Produces" annotated method, even in this case, it seams a looot of work just to create an object! But of course you need to create several, one for every network, how do you do that with DI?
I inject PingService in the client.
Seems legitimate, but PingService depends on PingParams, which takes us to injection point number 1.
Seems to me like the only appropriate way to use DI is with classes which have no dependencies (therefore useless) or with very simple service classes where you pass all the dependencies as parameters to service methods. For example a PingService which accepts the ip and the PingParams in the ping method, again this class would have no dependencies...
Am I missing something? How can you use DI with these "data" classes, classes which contain only fields for keeping data (PingParams)? Are suppose to avoid DI in these cases? Thanks
In general you should only use dependency injection for non-data classes. If you have classes that contain both data and non-data collaborators you can use assisted injection.
The ping params you talk about should indeed be bound to an instance on the start-up of your application and injected where necessary. For you example that is indeed much code but in the long run it keeps things nice and clean in bigger projects.
To summarize: bind PingParam when the application starts (as a Singleton for example), inject it into PingService, and create PingResult without DI (as you have done).
For Dependency Injection best practices, I recommend reading Dependency Injection by Prasanna
Assuming we're talking about CDI/Weld. Let's say your PingParams class were stored in the DB, as configuration loaded from some table. It would make a lot of sense to abstract that away, and simply provide a producer method for the PingParams class that reads the data from the DB and provides back this data element. It's not a bad idea to use a data object for this configuration, and provide a producer for it.
I am developing a MongoDB app with Java but I think this question related to datastore connections for web apps in general.
I like to structure all web apps with four top-level packages which are called (which I think will be self explanatory):
Controller
Model
Dao
Util
Ideally I would like to have a class in the Dao package that handles all the connections details.
So far I have created a class that looks like this:
public class Dao {
public static Mongo mongo;
public static DB database;
public static DB getDB() throws UnknownHostException, MongoException{
mongo = new Mongo("localhost");
database = mongo.getDB("mydb");
return database;
}
public static void closeMongo(){
mongo.close();
}
}
I use it in my code with something like this
public static void someMethod(String someData){
try {
DB db = Dao.getDB();
DBCollection rColl = db.getCollection("mycollection");
// perform some database operations
Dao.closeMongo();
} catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace();
}
}
This seems to work fine, but I'd be curious to know what people think is the "best" way to handle this issue, if there is such a thing.
The rule of thumb when connecting to relational database server is to have a pool. For example if you connect to an oracle database using a pool gives you some performance benefits both in terms of connection setup time and sql parsing time (if you are using bind variables). Other relational database may vary but my opinion is that a pool is a good pattern even for some other reason (eg. you may want to limit the maximum number of connections with your db user). You are using MongoDB so the first thing to check is how MongoDB handles connections, how expnsive is creating a connection,etc. I suggest to use/build a class that can implements a pool logic because it gives you the flexibility you may need in the future. Looking at your code it seems that you api
DB db=Dao.getDB();
should be paired with:
Dao.closeDB(DB db);
So you have a chance to really close the connection or to reuse it without affecting the Dao code. with these two methods can switch the way you manage connections without recoding the Dao objects
I would suggest you can write a java class to establish the connection with the database.
The arguments to the method should be the database name, password, host port and other necessary credentials.
You can always call the parametrized constructor everywhere where there is a need to establish database connectivity. This can be a model.
I got a 'nice' solution from this article. http://www.lennartkoopmann.net/post/722935345
Edit Since that link is dead, here's one from waybackmachine.org
http://web.archive.org/web/20120810083748/http://www.lennartkoopmann.net/post/722935345
Main Idea
What I found interesting was the use of a static synchronised method that returns an instance of the static class and its variables. Most professional devs probably find this obvious. I found this to be a useful pattern for managing the db connections.
Pooling
Mongo does automatic connection pooling so the key is to use just one connection to the datastore and let it handle its own pooling.
I think it is better if you call a method inside DAO to get data from database as well. If you do it in this way, say your database got changed. Then you have to edit many classes if you get data directly calling db queries. So if you separate db calling methods inside the DAO class itself and call that method to get data it is better.