日期:2014-05-16 浏览次数:20519 次
public class FullNameKeyCreator implements SecondaryKeyCreator {
private TupleBinding theBinding;
public FullNameKeyCreator(TupleBinding theBinding1) {
theBinding = theBinding1;
}
public boolean createSecondaryKey(SecondaryDatabase secDb,
DatabaseEntry keyEntry,
DatabaseEntry dataEntry,
DatabaseEntry resultEntry) {
try {
PersonData pd = (PersonData) theBinding.entryToObject(dataEntry);
String fullName = pd.getFamiliarName() + " " + pd.getSurname();
resultEntry.setData(fullName.getBytes("UTF-8"));
} catch (IOException willNeverOccur) {}
return true;
}
}
DatabaseConfig myDbConfig = new DatabaseConfig();
SecondaryConfig mySecConfig = new SecondaryConfig();
myDbConfig.setAllowCreate(true);
mySecConfig.setAllowCreate(true);
mySecConfig.setSortedDuplicates(true);
Environment myEnv = null;
Database myDb = null;
SecondaryDatabase mySecDb = null;
try {
String dbName = "myPrimaryDatabase";
myEnv = new Environment(new File("/tmp/JEENV"), null);
myDb = myEnv.openDatabase(null, dbName, myDbConfig);
TupleBinding myTupleBinding = new MyTupleBinding();
FullNameKeyCreator keyCreator =
new FullNameKeyCreator(myTupleBinding);
mySecConfig.setKeyCreator(keyCreator);
String secDbName = "mySecondaryDatabase";
mySecDb = myEnv.openSecondaryDatabase(null, secDbName, myDb,
mySecConfig);
} catch (DatabaseException de) {
}finally {
//close的顺序要注意下
try {
if (mySecDb != null) {
mySecDb.close();
}
if (myDb != null) {
myDb.close();
}
if (myEnv != null) {
myEnv.close();
}
} catch (DatabaseException dbe) {
}
}