2012-10-28 23:53:26 +01:00
|
|
|
package com.Acrobot.Breeze.Database;
|
|
|
|
|
|
|
|
import com.google.common.base.Joiner;
|
|
|
|
|
|
|
|
import javax.persistence.Entity;
|
2012-11-02 20:12:46 +01:00
|
|
|
import javax.persistence.Id;
|
2012-10-28 23:53:26 +01:00
|
|
|
import java.lang.annotation.AnnotationFormatError;
|
|
|
|
import java.lang.reflect.Field;
|
|
|
|
import java.util.LinkedList;
|
|
|
|
import java.util.List;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Parses an entity (class with database fields)
|
|
|
|
*
|
|
|
|
* @author Acrobot
|
|
|
|
*/
|
|
|
|
public class EntityParser {
|
|
|
|
private Class entity;
|
|
|
|
|
|
|
|
public EntityParser(Class table) {
|
|
|
|
if (!table.isAnnotationPresent(Entity.class) || !table.isAnnotationPresent(javax.persistence.Table.class)) {
|
|
|
|
throw new AnnotationFormatError("The class hasn't got Entity or Table annotation!");
|
|
|
|
}
|
|
|
|
|
|
|
|
entity = table;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Parses the class' fields to a standard SQL format
|
|
|
|
*
|
|
|
|
* @return SQLed class
|
|
|
|
*/
|
|
|
|
public String parseToString() {
|
|
|
|
List<String> fields = new LinkedList<String>();
|
|
|
|
|
|
|
|
for (Field field : entity.getDeclaredFields()) {
|
|
|
|
fields.add(convertToSQL(field));
|
|
|
|
}
|
|
|
|
|
|
|
|
return Joiner.on(',').join(fields);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Converts a field type to SQL type
|
|
|
|
*
|
|
|
|
* @param field Java's field
|
|
|
|
* @return SQL type
|
|
|
|
*/
|
2012-11-02 20:48:14 +01:00
|
|
|
public static String convertToSQL(Field field) {
|
2012-11-03 20:40:16 +01:00
|
|
|
String sqlType = field.getName();
|
2012-11-02 20:12:46 +01:00
|
|
|
Class<?> type = field.getType();
|
|
|
|
|
2012-11-02 20:48:14 +01:00
|
|
|
if (type.isAssignableFrom(boolean.class)) {
|
2012-11-03 20:40:16 +01:00
|
|
|
sqlType += " BOOLEAN";
|
2012-11-02 20:12:46 +01:00
|
|
|
} else if (type.isAssignableFrom(int.class)) {
|
2012-11-03 20:40:16 +01:00
|
|
|
sqlType += " INTEGER";
|
2012-11-02 20:48:14 +01:00
|
|
|
} else if (type.isAssignableFrom(double.class) || type.isAssignableFrom(float.class)) {
|
2012-11-03 20:40:16 +01:00
|
|
|
sqlType += " REAL";
|
2012-11-02 20:12:46 +01:00
|
|
|
} else {
|
2012-11-03 20:40:16 +01:00
|
|
|
sqlType += " TEXT";
|
2012-11-02 20:12:46 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if (field.isAnnotationPresent(Id.class)) {
|
2012-11-02 20:48:14 +01:00
|
|
|
sqlType += " PRIMARY KEY";
|
2012-11-02 20:12:46 +01:00
|
|
|
}
|
|
|
|
|
2012-11-02 20:48:14 +01:00
|
|
|
return sqlType;
|
2012-10-28 23:53:26 +01:00
|
|
|
}
|
|
|
|
}
|