와 나는 이것에 대해 정보를 찾기 위해 시도했지만 빈손으로 올라와있다 :만들기 클래스를 동적으로 자바
나는 반사 또는 프록시를 사용하여 자바에서 동적으로 클래스를 만들 수 있습니다하지만 난 찾을 수 없습니다 수집 방법. 리플렉션을 사용하여 SQL 쿼리를 만드는 간단한 데이터베이스 프레임 워크를 구현하고 있습니다. 이 메서드는 데이터베이스 필드를 매개 변수로 사용하여 개체를 가져오고이를 기반으로 쿼리를 만듭니다. 그러나 객체 자체를 동적으로 생성 할 수 있다면 각 테이블에 대해 간단한 데이터 래퍼 객체를 가질 필요가 없다면 매우 유용 할 것입니다.
동적 클래스는 간단한 필드 (String
, Integer
, Double
) 만 필요합니다.
public class Data {
public Integer id;
public String name;
}
이 방법이 가능하며 어떻게해야합니까?
편집 : 이것은 내가 본을 사용하는 방법입니다
/** Creates an SQL query for updating a row's values in the database.
*
* @param entity Table name.
* @param toUpdate Fields and values to update. All of the fields will be
* updated, so each field must have a meaningful value!
* @param idFields Fields used to identify the row(s).
* @param ids Id values for id fields. Values must be in the same order as
* the fields.
* @return
*/
@Override
public String updateItem(String entity, Object toUpdate, String[] idFields,
String[] ids) {
StringBuilder sb = new StringBuilder();
sb.append("UPDATE ");
sb.append(entity);
sb.append("SET ");
for (Field f: toUpdate.getClass().getDeclaredFields()) {
String fieldName = f.getName();
String value = new String();
sb.append(fieldName);
sb.append("=");
sb.append(formatValue(f));
sb.append(",");
}
/* Remove last comma */
sb.deleteCharAt(sb.toString().length()-1);
/* Add where clause */
sb.append(createWhereClause(idFields, ids));
return sb.toString();
}
/** Formats a value for an sql query.
*
* This function assumes that the field type is equivalent to the field
* in the database. In practice this means that this field support two
* types of fields: string (varchar) and numeric.
*
* A string type field will be escaped with single parenthesis (') because
* SQL databases expect that. Numbers are returned as-is.
*
* If the field is null, a string containing "NULL" is returned instead.
*
* @param f The field where the value is.
* @return Formatted value.
*/
String formatValue(Field f) {
String retval = null;
String type = f.getClass().getName();
if (type.equals("String")) {
try {
String value = (String)f.get(f);
if (value != null) {
retval = "'" + value + "'";
} else {
retval = "NULL";
}
} catch (Exception e) {
System.err.println("No such field: " + e.getMessage());
}
} else if (type.equals("Integer")) {
try {
Integer value = (Integer)f.get(f);
if (value != null) {
retval = String.valueOf(value);
} else {
retval = "NULL";
}
} catch (Exception e) {
System.err.println("No such field: " + e.getMessage());
}
} else {
try {
String value = (String) f.get(f);
if (value != null) {
retval = value;
} else {
retval = "NULL";
}
} catch (Exception e) {
System.err.println("No such field: " + e.getMessage());
}
}
return retval;
}
같은 클래스의 ArrayList를을 만드는 오전. –
개인적으로 데이터베이스 모델에 매핑되는 Java 모델을 사용하는 데 문제가 발생하지 않습니다. 또한 SQL 쿼리를 만들 때 SQL 문자열을 작성하는 대신 PreparedStatements를 사용하여 SQL 주입을 피하십시오. – JeeBee