For example i have a Resultset which contain Details about Employee details and I have a table For Employee in database and i am selecting all details from that
I have java POJO class which resembles Employee Table what is the best method to implement convert result set into Employee class object
what is the best way to implement if i have multiple classes Like Employee and multiple tables too how to write a reusable code.
I am Using following notation now.
public Employee{
private int empId;
public setEmpId(int empId){
this.empId = empId;
}
public int getEmpId(){
return this.empId;
}
}
public class SetResultSetToEmployee{
public Employee getEmployee(){
Employee e = new Employee();
e.setEmpId(resultSet.getInt("EmpId"));
return e;
}
}
Mybatis, or ORM like Hibernate may be your best solution.
But, if you really need to use jdbc's ResultSet, and want to convert ResultSet into java Beans, you can check:
If you are aware of
JPA
, then that will be best bet.. You won't have to do a typecast to get your POJO object.. JPA works on ORM (Object Relational Mapping). It directly Maps yourPOJO
object to Database table.. And when you can directly fetch your object from database..And if you have no other choice than using
JDBC
, then you have no other choice thanTypeCasting
.In case of JDBC, I don't know what kind of Re-usability you are looking for, but you can implement a
DB
class, and have all yourQuery Templates
there.. For any query you want to execute, you can use that class.. That be comparatively better to go with rather than have discrete queries, scattered all over your application..Again if you can use JPA, there is a concept of
Entities
.. If you want to work with multiple fetch, update or insert with database, it will be easier for you.. You can just get appropriate object and dump it in a instance of yourEntity
, or dump your object into your database without worrying about any kind ofQueries
.For a start of JPA, you can start with any of these links: -
If you really want to write reusable codes use ORM tools like http://www.hibernate.org/.