我应该编写一些代码来从oracle数据库读取和写入数据。 IO是用sql处理的,但问题出在java类中,它存储来自每个元组的数据。
到目前为止,我已经编写了一个父抽象类来表示任何表中的任何元组。然后我就为每一张桌子写了每一堂课。这很乏味,我相信有更聪明的方法可以做到这一点。每个类基本相同,但具有不同名称的不同属性,更改它们时很容易出错。
父类是这样的:
public abstract class DBEntity {
String entName;
String key;
String insertFormat;
String values;
boolean isSet;
public boolean addTo(OracleHelper db) {
return db.sentence(insertValues());
}
public abstract String insertValues();
public boolean add(OracleHelper db) {
return db.sentence(insertValues());
}
public String find(OracleHelper db, String key) {
return db.query("select * from " + entName + "where " + this.key + " = " + key);
}
public String[] find(OracleHelper db, String value, String attribute) {
return db.query("select * from " + entName + "where " + attribute + " = " + value).split("\n");
}
public abstract DBEntity[] getEntities(OracleHelper db, String value, String attribute) throws IncorrectConstructionValues;
}
儿童班是这样的:
public class Genre extends DBEntity {
String name;
String description;
static String entName = "genre";
static String insertFormat = "insert into genre(name, description) values('%s', '%s')";
int PARAM_NUM = 4;
public Genre(String name, String description) {
this.name = name;
this.description = description;
isSet = true;
}
public Genre() {
isSet = false;
}
/**
* Creates a Game with the first result of the value-attribute combination.
* If you're sure there is only one possible match use this. Else use another
* combination.
*
* @param db
* @param attribute
* @param value
* @throws IncorrectConstructionValues
*/
public Genre(OracleHelper db, String attribute, String value) throws IncorrectConstructionValues {
try {
String[] params = find(db, attribute, value)[0].split("||");
name = params[0];
description = params[1];
} catch (Exception e) {
throw new IncorrectConstructionValues("No hay ningún elemento con esos valores");
}
isSet = true;
}
public Genre(String allValues) throws IncorrectConstructionValues {
try {
String[] params = allValues.split("||");
name = params[0];
description = params[1];
} catch (Exception e) {
throw new IncorrectConstructionValues("Algún valor no corresponde" +
"con el de un atributo para esta clase");
}
isSet = true;
}
@Override
public String insertValues() {
if (isSet) {
return String.format(insertFormat, name, description);
} else {
return null;
}
}
@Override
public DBEntity[] getEntities(OracleHelper db, String value, String attribute) throws IncorrectConstructionValues {
String[] tuples = find(db, value, attribute);
Genre[] games = new Genre[tuples.length];
for (int i = 0; i < games.length; i++) {
games[i] = new Genre(tuples[i]);
}
return games;
}
}
有没有更好的简单方法呢?