How can I create a single add method that will insert different entities in the jdbc? I want to use annotations and reflection for that.
I have created 2 annotations:
(...)
public @interface Column {
String name();
boolean isPrimaryKey() default false;
}
and
(...)
public @interface Table {
String name();
}
Suppose we have 2 entities/models/etc. : Client and Waiter. For both we should make 2 add methods, each with own INSERT.
If we have like 4 entities, we should have 4 add methods for each entity. Instead of having 4 add methods, how can I make just 1 add method? and by using the annotations and the reflection.
Eg:
@Table(name = "Table_Client")
public class Client{
@Column(name = "ID", isPrimaryKey = true)
private long id;
@Column(name = "FULL_NAME")
private String name;
}
@Table(name = "Table_Waiter")
public class Waiter {
@Column(name = "FULL_NAME", isPrimaryKey = true)
private String name;
@Column(name = "AGE")
private int age;
}
case: db.add(Client c1) => add to the database in the table Table_Client the client c1
db.add(Waiter w1) => add to the database in the table Table_Waiter the waiter w1
and so on...
My idea is to take the class of the given object and scan it for the TYPE annotation to get the table's name. Then, take all the field's annotations and make a dynamic INSERT INTO VALUES query, but the problem is that I can't actually do that, because I can't pass the object's arguments.
Another question: if this can be done, update and delete methods can follow the same path?