I’m trying to create a method in java for create table in database in mysql I have two classes
first class name is User.java
public class User {
private int userId;
private String userName;
private String userEmail;
private String userPassword;
// getters and setters
}
second class name is Post.java
public class Post {
private int postId;
private String postCategory;
private String postTitle;
private String post;
private int userId; // foreign key
// getters and setters
}
my createTable method
public String createTable(Class<?> testDBClass) throws IllegalAccessException {
String message = "";
String className = printClassName(TestDBCode.class);
StringBuilder sql = new StringBuilder("CREATE TABLE IF NOT EXISTS " + className);
sql.append("(");
// getting fields
Field[] fields = testDBClass.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 foreign key or which table not?
this method works perfectly for creating table without foreign key but I don’t get the logic for foreign key I want to create a method createTable()
which works well for both table with foreign key and table without foreign key. I can achieve this task by creating annotations but I don’t want annotation because every time and every annotation need to process annotation first. so, I don’t want annotation give me better solution and help me to solve my problem.