實現了OWL本體到MySQL的儲存和讀取,首先應該配置好環境,在項目中添加jena的相關包,值得注意的是MySQL的驅動和版本要一致。
我是用protege建立OWL本體,然後再從OWL檔案中讀取,存入MySQL資料庫,注意在儲存OWL本體的時候最好項目另存新檔的LANGUAGE選擇RDF/XML,最好用UTF-8編碼,這樣讀取出錯的機會少一些,圖片在附件中。
下面是操作的java代碼:
/* 串連資料庫 */
public static IDBConnection connectDB(String DB_URL, String DB_USER,
String DB_PASSWD, String DB_NAME) {
return new DBConnection(DB_URL, DB_USER, DB_PASSWD, DB_NAME);
}
/* 從檔案讀取本體並將其存入資料庫 */
public static OntModel createDBModelFromFile(IDBConnection con, String name,
String filePath) {
ModelMaker maker = ModelFactory.createModelRDBMaker(con);
Model base = maker.createModel(name);
OntModel newmodel = ModelFactory.createOntologyModel(
getModelSpec(maker), base);
newmodel.read(filePath);
return newmodel;
}
/* 從資料庫中得到已存入本體 */
public static OntModel getModelFromDB(IDBConnection con, String name) {
ModelMaker maker = ModelFactory.createModelRDBMaker(con);
Model base = maker.getModel(name);
OntModel newmodel = ModelFactory.createOntologyModel(
getModelSpec(maker), base);
return newmodel;
}
public static OntModelSpec getModelSpec(ModelMaker maker) {
OntModelSpec spec = new OntModelSpec(OntModelSpec.OWL_MEM);
spec.setImportModelMaker(maker);
return spec;
}
下面是測試的代碼,先從檔案中讀取,讓後存入資料庫中,再從資料庫中讀出。
public static void test() {
String DB_URL = "jdbc:mysql://localhost/expert";
String DB_USER = "root";
String DB_PASSWD = "root";
String DB = "MySQL";
String DB_DRIVER = "com.mysql.jdbc.Driver";
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String filePath = "file:C://expert//Expert.rdf-xml.owl";
IDBConnection con = JaneUtils.connectDB(DB_URL,DB_USER, DB_PASSWD, DB);
System.out.println(con);
JaneUtils.createDBModelFromFile(con, "expert",filePath);
OntModel model = JaneUtils.getModelFromDB(con, "expert");
JaneUtils.SimpleReadOntology(model);
}
/* 簡單讀取本體中的各個class */
public static void SimpleReadOntology(OntModel model) {
for (Iterator i = model.listClasses(); i.hasNext();) {
OntClass c = (OntClass) i.next();
System.out.println(c.getLocalName());
}
}
此主題相關圖片如下: