I want to create a library(Jar file) in Java which would contain all my methods for the database we use. There are about 60 methods in there so I would like to make it more orga
Here some snapshot of my custom library for connect to database:
PostgreConnection.java
public class PostgreConnection {
private static Connection conn;
public Connection makeConnection(String url, String db, String username, String password) {
if (conn == null) {
try {
Class.forName(Constants.POSTGRES_DRIVER);
conn = DriverManager.getConnection(Constants.POSTGRES_URL + url + "/" + db, username, password);
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(PostgreConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
return conn;
}
}
Constants.java
public class Constants {
public static String POSTGRES_URL = "jdbc:postgresql://";
public static String POSTGRES_DRIVER = "org.postgresql.Driver";
}
In org.ert.model
you can store all the Model
that you need based on the tables of your database.
NotifyCharts.java
public class NotifyCharts {
private Integer Id;
private String revName;
private Date importDate;
private Integer pages;
private Boolean status;
public Integer getId() {
return Id;
}
public void setId(Integer Id) {
this.Id = Id;
}
public Date getImportDate() {
return importDate;
}
public void setImportDate(Date importDate) {
this.importDate = importDate;
}
public Integer getPages() {
return pages;
}
public void setPages(Integer pages) {
this.pages = pages;
}
public String getRevName() {
return revName;
}
public void setRevName(String revName) {
this.revName = revName;
}
public Boolean isStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
}
SQLQuery
is an abstract class
for some basic method such as insert, update, delete, etc
.
SQLQuery.java
public abstract class SQLQuery<T> {
protected void makeStatement(String url, String db, String username, String password) {
PostgreConnection connect = new PostgreConnection();
Connection con = connect.makeConnection(url, db, username, password);
try {
state = (Statement) con.createStatement();
} catch (SQLException ex) {
Logger.getLogger(SQLQuery.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String arrayBuilder(Object[] obj, boolean val) {
StringBuilder arr = new StringBuilder();
arr.append("(");
for (int i = 0; i < obj.length; i++) {
if (i < obj.length - 1) {
if (val) {
arr.append("'");
}
arr.append(obj[i]);
if (val) {
arr.append("'");
}
arr.append(", ");
} else {
if (val) {
arr.append("'");
}
arr.append(obj[i]);
if (val) {
arr.append("'");
}
}
}
arr.append(")");
return arr.toString();
}
public int insertRecord() throws SQLException {
StringBuilder query = new StringBuilder();
query.append("INSERT INTO ").append(tableName).append(arrayBuilder(columns, false)).append(" VALUES ").append(arrayBuilder(values, true));
return state.executeUpdate(query.toString());
}
public ResultSet getAll() throws SQLException {
StringBuilder query = new StringBuilder();
query.append("SELECT * FROM ").append(tableName);
rSet = state.executeQuery(query.toString());
return rSet;
}
public abstract void setColsAndVals(T t);
}
NotifyChartsSQL.java
is implementation of the abstract class
, org.ert.sql.impl
is package
to store all your implementation that you need.
NotifyChartsSQL.java
public class NotifyChartsSQL extends SQLQuery<NotifyCharts> {
public NotifyChartsSQL(String url, String db, String username, String password, NotifyCharts notify) {
makeStatement(url, db, username, password);
setColsAndVals(notify);
}
@Override
public final void setColsAndVals(NotifyCharts notify) {
Map<String, Object> objects = new HashMap<>();
String[] columns;
Object[] values;
if(notify.getId() != null)
objects.put("id", notify.getId());
if(notify.getRevName() != null)
objects.put("rev_name", notify.getRevName());
if(notify.getImportDate() != null)
objects.put("import_date", notify.getImportDate());
if(notify.getPages() != null)
objects.put("pages", notify.getPages());
objects.put("status", notify.isStatus());
columns = Arrays.copyOf(objects.keySet().toArray(), objects.size(), String[].class);
values = objects.values().toArray();
setColumns(columns);
setValues(values);
setTableName("notify_charts");
}
}
And last is the test
package that test your custom library to make sure that everything is ok.
TestMain.java
public class TestMain {
public static void main(String[] args) {
NotifyCharts notify = new NotifyCharts();
try {
notify.setRevName("Test456");
notify.setImportDate(new Date());
notify.setPages(10);
notify.setStatus(false);
NotifyChartsSQL notCharts = new NotifyChartsSQL("localhost:5432", "charts", "username", "password", notify);
int status = notCharts.insertRecord();
if (status == 1) {
System.out.println("Success Insert");
} else {
System.out.println("Failed Insert");
}
} catch (SQLException ex) {
Logger.getLogger(TestMain.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I suggest if you want to make this custom library if you using manual JDBC
and not using ORM
such as Hibernate
. Because in Hibernate is already provide all the methods that you need except do you want to add some special method you can do like duffymo said before. This idea of custom library is come from the DAO
and the Hibernate
structure.
Thanks for read it, and please learn some Design Pattern in Java if you want to make some custom library that more organized.
You could save yourself a lot of trouble and write a generic DAO:
package persistence;
public interface GenericDao<K, V> {
V find(K id);
List<V> find();
K save(V value);
void update(V value);
void delete(V value);
}
I'd forget about writing your own persistence classes and use a proven solution, like Spring JDBC template.
This problem has been solved many times, many ways. What do you hope to do to improve upon what exists? How will you justify the added expense of developing, testing, and maintaining this functionality?