0

我在 StoryModel 中创建了一些方法。如果代码中有任何错误,我真的很感激更正。

public class StoryModel {

    String dbName = "DB3";
    String sns =  "http://somebook/SemBook#";
    String ns;
    Dataset ds;
    OntModel om;

    // create model and connect to database
    public StoryModel(String storyName){

        ns = sns + storyName;
        ds = TDBFactory.createDataset(dbName);
        om = ModelFactory.createOntologyModel();

    }

    // create classes in model
    public void initModel() {

        om.createClass(ns + "Person");
        om.createClass(ns + "Event");
        om.createClass(ns + "Place");
        om.createClass(ns + "Time");
        om.createClass(ns + "Object");
        saveModel();
    }   

    //Read & write in database
    //Display it
    public void saveModel() {

        ds.begin(ReadWrite.WRITE);
        om.write(System.out, "RDF/XML-ABBREV");

    }

    // Create resource to class in model
    public Resource createResource(String resourceName, String clsName) {

        OntResource resource = om.createOntResource(ns + resourceName);
        String ruri = ns + resource;
        OntClass clsuri = om.getOntClass(ns + clsName);

        Individual i = om.createIndividual(ruri, clsuri);

        return i;

    }

    /*
     * Return an RDF resource object given the URI of the resource as a string. The
     * URI can be represented in full, or as a "prefix:localName".
     * @param resourceName The full URI of the resource
     * @return An RDF resource object
     */

    public Resource stringToResource( String resourceName ) {

        String resourceURI = om.expandPrefix( resourceName );

        return om.getResource( resourceURI );

    }

    // Delete the resource
    public void deleteResource(String resourceName) {

        try {
            OntResource resource = om.getOntResource(ns + resourceName);

            if (resource != null) 
            {
               resource.remove();
            }
            else {
                System.out.println("Resource not present");
            }   
        }
        catch (Exception e) { }         
    }
}

在 SemBookMain 中,我创建了一个模型并使用在 StoryModel 中创建的方法将类初始化为资源并显示它

public class SemBookMain {

    public static void main(String[] args) {

        // create and initialize a model
        StoryModel sm = new StoryModel("alice");
        //sm.saveModel();
        sm.initModel();

        // add resources
        String clsName = "Person";
        String[] ar = {"Alice", "Peter", "Ben", "Robin"};

        for (String r : ar) {

            Resource res = sm.createResource(r, clsName);

        }
        sm.saveModel();

    }

}

我真的很抱歉我在下面添加了输出作为评论,所以请参阅我的评论。

我不明白错误 1 ​​和 2 以及为什么不显示资源。我缺少一些东西,但无法弄清楚。

4

1 回答 1

2

ds.begin(ReadWrite.WRITE);但不是ds.commit

initModel打电话saveModel,然后你再打电话saveModel

遵循以下代码模式:

http://jena.apache.org/documentation/tdb/tdb_transactions.html#write-transactions

于 2013-03-15T13:35:38.877 回答