To store and read the owl ontology to MySQL, you must first configure the environment and add Jena packages to the project. It is worth noting that the MySQL driver and version must be consistent.
I used protege to create an owl ontology, read it from the owl file, and store it in the MySQL database. Note that when saving the owl ontology, it is best to select "RDF/XML" for the language saved in the project, it is best to use UTF-8 encoding, so that the chance of reading errors is less, the picture in the attachment.
The following is the Java Code :
/* connect to the database */
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 );
}< br>
/* read the ontology from the file and store it in the database */
Public static ontmodel createdbmodelfromfile (idbconnection con, string name,
string filepath) {
modelmaker = modelfactory. createmodelrdbmaker (CON);
model base = maker. createmodel (name);
ontmodel newmodel = modelfactory. createontologymodel (
getmodelspec (maker), base);
newmodel. read (filepath);
return newmodel;
}
/* Obtain the stored ontology from the database */
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;
}
The following is the test code. Read the code from the file, store it in the database, and read it from the database.
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. 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 );
}
/* Simply read each class in the ontology */
Public static void simplereadontology (ontmodel model ){
For (iterator I = model. listclasses (); I. hasnext ();){
Ontclass c = (ontclass) I. Next ();
System. Out. println (C. getlocalname ());
}
}
The image of this topic is as follows: