I'm trying to create a method in Java to create a table in a MySQL database. I have two classes:
public class User {
private int userId;
private String userName;
private String userEmail;
private String userPassword;
// getters and setters
}
public class Post {
private int postId;
private String postCategory;
private String postTitle;
private String post;
private int userId; // foreign key
// getters and setters
}
createTable()
methodpublic String createTable(Class<?> users) throws IllegalAccessException {
String message = "";
String className = printClassName(User.class);
StringBuilder sql = new StringBuilder("CREATE TABLE IF NOT EXISTS " + className);
sql.append("(");
// getting fields
Field[] fields = users.getDeclaredFields();
for ( int i = 0; i < fields.length; i++ ) {
if ( fields[i].getType() == int.class && fields[i].getName().equals("userId")) {
sql.append(fields[i].getName()).append(" INT AUTO_INCREMENT NOT NULL");
} else if ( fields[i].getType() == int.class ) {
sql.append(fields[i].getName()).append(" INT NOT NULL");
} else if ( fields[i].getType() == String.class ) {
sql.append(fields[i].getName()).append(" VARCHAR(255) NOT NULL");
}
if ( i < fields.length - 1 ) {
sql.append(", ");
}
if ( i == fields.length - 1 ) {
sql.append("PRIMARY KEY (").append(fields[0].getName()).append(")");
}
}
sql.append(");");
System.out.println("Executing Sql Query: "+ sql.toString());
try {
int i = 0;
dataBaseConnection.pstmt = dataBaseConnection.conn.prepareStatement(sql.toString());
i = dataBaseConnection.pstmt.executeUpdate();
if ( i > 0 ) {
message = "table created with name: " + className + " successfully...";
} else {
message = "something went wrong...";
}
} catch (Exception e) {
e.printStackTrace();
}
return message;
}
The problem is to how to know which table has a foreign key and which table does not?
This method works perfectly for creating tables without foreign keys, but I don't get the logic for ones with a foreign key. I want to create a method createTable()
which works well for both kinds of tables. I can achieve this task by creating annotations, but I don't want annotation because every time the annotation needs to be processed first. I am looking for an alternate solution.
Since you're already using reflection, you can do the same here to check the name of the field to see if it contains id
. Change your primary key for each class to just be called id
, so all other ___Id
's are easily identified as foreign keys.
public class Post {
private int id;
// ...
}
public class User {
private int id;
// ...
}
(Alternatively, you could check the name of the class using reflection and ignore the field that contains the name of the class.)
Field[] fields = users.getDeclaredFields();
for ( int i = 0; i < fields.length; i++ ) {
if (fields[i].getName().contains("Id")) {
// This field is a foreign key
}
}