`
yydcj
  • 浏览: 59683 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

使用jena持久化OWL本体到MySQL

阅读更多

引自http://www.cnblogs.com/armymen1980/archive/2008/10/22/1316699.html

实现了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());
    }
}


此主题相关图片如下:
按此在新窗口浏览图片

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics