您的位置:首页 > 数据库 > MySQL

使用jena持久化OWL本体到MySQL

2014-11-16 10:53 357 查看
http://jvzizh.blog.163.com/blog/static/15733583200982145631382/

遇到了好多问题,终于实现了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());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: