NimChimpsky
NimChimpsky

Reputation: 47290

generate sql from java class

I have java class, no annotations, not using hibernate.

I want to create an appropriate sql schema object.

Can I auto generate this using intellij or anything else ?

public class MyClass {
Long id;
String name;
}

would create this

CREATE TABLE public.employee (
    id bigint NOT NULL DEFAULT,
    name text NOT NULL
)

Upvotes: 0

Views: 2385

Answers (1)

Anirudh
Anirudh

Reputation: 457

This is one of the custom method that can be written to generate such queries

public static void main(String[] args) throws ParseException {
    Field[] fields = MyClass.class.getDeclaredFields();
    String query = "CREATE TABLE public.employee(";
    for(int i=0;i<fields.length;i++){
        if(fields[i].getType().getSimpleName().toLowerCase().equals("long") || fields[i].getType().getSimpleName().toLowerCase().contains("int")){
            query += fields[i].getName()+" bigint NOT NULL";
        }
        else if (fields[i].getType().getSimpleName().toLowerCase().contains("double") || fields[i].getType().getSimpleName().toLowerCase().equals("float")){
            query += fields[i].getName()+" float NOT NULL";
        }
        else if (fields[i].getType().getSimpleName().toLowerCase().contains("string")){
            query += fields[i].getName()+" text NOT NULL";
        }
        if(i != fields.length-1)
            query+=",";
    }
    query+=")";
    System.out.println(query);
}

Upvotes: 5

Related Questions