jena 简单查询2(推理)

//DbUtil连接数据库
//a likes b,b likes c-> a likes c
  


import com.hp.hpl.jena.rdf.model.*;  
import com.hp.hpl.jena.db.DBConnection;
import com.hp.hpl.jena.db.IDBConnection;
import com.hp.hpl.jena.db.ModelRDB;
import com.hp.hpl.jena.ontology.*;  
import com.hp.hpl.jena.query.*;
import com.hp.hpl.jena.reasoner.Reasoner;
import com.hp.hpl.jena.reasoner.rulesys.GenericRuleReasoner;
import com.hp.hpl.jena.reasoner.rulesys.Rule;
import com.hp.hpl.jena.util.PrintUtil;


public class TestJena  {
	

	static String URI="http://owl.man.ac.uk/2006/07/sssw/people#";
	static String filePath="F:\\Ontology1385473236444.owl";
		public static void main(String[] args) {
		// TODO Auto-generated method stub
		//创建一个默认本体
		TestJena st=new TestJena();
		//规则前缀
		 PrintUtil.registerPrefix("iqas", URI);
		 try{
		 DbUtil.getConnection().cleanDB();
		 }catch( Exception e){}
		 ModelMaker mMaker=st.getModelMaker(DbUtil.getConnection());
		 Model base=mMaker.createModel(URI,false);
			//建立本体模型,内存OWL_DL模型,无base;
		 OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM,base);
		//通过本体得到其关联的文档管理器
		OntDocumentManager dm = m.getDocumentManager();
		//在文档管理器中将要导入的文档与一个统一资源定位符关联;
		dm.addAltEntry( URI, "file:"+ filePath    );
		//读取文档到模型中;
		 m.read( URI);
		 
		//定义规则
		 String rule=
		 "[r1:(?a iqas:likes ?b),(?b iqas:likes ?c)->(?a iqas:likes ?c)]"+
		 "[r2:(?a iqas:has_pet ?b)->(?a iqas:likes ?b)]"+
		 "[r2:(?a iqas:likes ?b)->(?a iqas:like ?b)]";
		  String query="PREFIX iqas: SELECT ?x WHERE {iqas:Com1 iqas:likes ?x }";
		  
		  Reasoner reasoner=new GenericRuleReasoner(Rule.parseRules(rule));
		  
		  InfModel infModel=ModelFactory.createInfModel(reasoner, m);

		Query qu1=QueryFactory.create(query);
		QueryExecution exc=QueryExecutionFactory.create(qu1,infModel);
		ResultSet rst=exc.execSelect();

		ResultSetFormatter.out(System.out,rst,qu1);
		

		//m以mMaker为基础,所以存有数据库连接信息
		 m.commit();
		  m.close();
		  
		  IDBConnection icon=DbUtil.getConnection();
		  //构造ModelRDB 从数据库中取出存入的模型,用到连接和名字
		  ModelRDB mModel= ModelRDB.open(icon, URI);

		
	}
	public ModelMaker getModelMaker(DBConnection con){
		   try {
	            // Create a model maker object
			   
	            return ModelFactory.createModelRDBMaker(con);
	        }
	        catch (Exception e) {
	            e.printStackTrace();
	            System.exit( 1 );
	        }
	        return null;
		
	}

}


 

你可能感兴趣的:(Ontology)