기은P
시간이 멈추는 장소
기은P
  • Programming (272)
    • 개발노트 (1)
    • FrontEnd (56)
      • ES&JS 문법 (14)
      • HTML&CSS (4)
      • React 기본 (18)
      • React 심화 (12)
      • React 이슈 (2)
      • Project 연습 (1)
      • Next.js (5)
    • Backend&Devops (33)
      • AWS (2)
      • Docker (9)
      • Jenkins (6)
      • Nginx (6)
      • Node.js (1)
      • ElasticSearch (5)
      • 프레임워크&아키텍처 (2)
      • 암호화 (0)
      • 기타 (2)
    • 알고리즘 (3)
    • C# (8)
      • WPF (8)
    • Java (51)
      • 순수 Java (18)
      • RDF&Jena (12)
      • RCP&GEF (9)
      • JMX (5)
      • JMapper (3)
      • 오류해결 (4)
    • Database (21)
      • RDBMS (9)
      • NoSQL (2)
      • TSDB (1)
      • GraphQL (1)
      • Hibernate (3)
      • 데이터베이스 이론 (4)
      • Redis (1)
    • 프로토콜 (11)
      • Netty (4)
      • gRPC (5)
      • 프로토콜 개념 (2)
    • Server (4)
      • Linux (4)
    • 2020 정보처리기사 필기 (43)
      • 목차 (1)
      • 기출문제 (1)
      • 1과목 - 소프트웨어 설계 (6)
      • 2과목 - 소프트웨어 개발 (7)
      • 3과목 - 데이터베이스 구축 (8)
      • 4과목 - 프로그래밍 언어 활용 (7)
      • 5과목 - 정보시스템 구축 관리 (10)
    • 2020 정보처리기사 실기 (31)
      • 목차 (4)
      • 기출예상문제 (19)
      • 실기요약 (8)
    • 빅데이터분석기사 필기 (4)
      • 목차 (0)
      • 필기 요약 (3)
    • 전기 공학 (1)
      • CIM (1)
    • 산업자동화시스템 (3)
      • SCADA (1)
      • OPC UA (2)
    • 디자인패턴 (1)
    • 휴지통 (0)

공지사항

  • 공지사항/포스팅 예정 항목

최근 댓글

최근 글

전체 방문자
오늘
어제

티스토리

hELLO · Designed By 정상우.
기은P

시간이 멈추는 장소

Java/RDF&Jena

Jena TDB CRUD 사용

2020. 3. 27. 17:05
반응형

Jena TDB CRUD 사용

 

 

 

Maven Dependency 추가
<dependency>
  		<groupId>org.apache.jena</groupId>
  		<artifactId>jena-fuseki</artifactId>
  		<version>1.1.1</version>
  	</dependency>
  	<dependency>
  		<groupId>org.apache.jena</groupId>
  		<artifactId>apache-jena-libs</artifactId>
  		<type>pom</type>
  		<version>2.13.0</version>
  	</dependency>

 

Jena용 라이브러리를 pom.xml에 추가해준다.

 

 

 

 

TDB Controller 클래스 생성
public class TDBControll {
	private Dataset ds;

	// TDB용 데이터셋을 생성한다.
	public void TDBConnection(String path) {
		ds = TDBFactory.createDataset(path);
	}

	// TDB에서 온톨로지 또는 모델을 읽어온다.
	public void loadModel(String modelName, String path) {
		Model model = null;
		ds.begin(ReadWrite.WRITE);
		try {
			model = ds.getNamedModel(modelName);
			FileManager.get().readModel(model, path);
			ds.commit();
		} finally {
			ds.end();
		}
	}

	// TDB Store에 triple을 추가한다.
	public void addStatement(String modelName, String subject, String property, String object) {
		Model model = null;

		ds.begin(ReadWrite.WRITE);
		try {
			model = ds.getNamedModel(modelName);
			Statement stmt = model.createStatement(model.createResource(subject), model.createProperty(property),
					model.createResource(object));
			model.add(stmt);
			ds.commit();
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			if (model != null)
				model.close();
			ds.end();
		}
	}

	// TDB Store에서 triple을 읽어온다.
	public List<Statement> getStatements(String modelName, String subject, String property, String object) {
		List<Statement> results = new ArrayList<Statement>();
		Model model = null;

		ds.begin(ReadWrite.READ);
		try {
			model = ds.getNamedModel(modelName);

			Selector selector = new SimpleSelector((subject != null) ? model.createResource(subject) : (Resource) null,
					(property != null) ? model.createProperty(property) : (Property) null,
					(object != null) ? model.createResource(object) : (RDFNode) null);

			StmtIterator it = model.listStatements(selector);
			{
				while (it.hasNext()) {
					Statement stmt = it.next();
					results.add(stmt);
				}
			}
			ds.commit();
		} finally {
			// TODO: handle finally clause
			if (model != null)
				model.close();
			ds.end();
		}
		return results;
	}
	// TDB Store에서 triple을 삭제한다. 
	public void removeStatement(String modelName, String subject, String property, String object) {
		Model model = null;

		ds.begin(ReadWrite.WRITE);
		try {
			model = ds.getNamedModel(modelName);

			Statement stmt = model.createStatement(model.createResource(subject), model.createProperty(property),
					model.createResource(object));

			model.remove(stmt);
			ds.commit();
		} finally {
			if (model != null)
				model.close();
			ds.end();
		}
	}

	public void close() {
		ds.close();
	}
}

 

 

 

 

Main에서의 Controller 사용
public class Main {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TDBControll tdb = null;

		String URI = "https://tutorial-academy.com/2015/tdb#";

		String namedModel1 = "Model_German_Cars";
		String namedModel2 = "Model_US_Cars";

		String john = URI + "John";
		String mike = URI + "Mike";
		String bill = URI + "Bill";
		String owns = URI + "owns";

		tdb = new TDBControll();
		tdb.TDBConnection("tdb");
		
		// named Model 1
		tdb.addStatement(namedModel1, john, owns, URI + "Porsche");
		tdb.addStatement(namedModel1, john, owns, URI + "BMW");
		tdb.addStatement(namedModel1, mike, owns, URI + "BMW");
		tdb.addStatement(namedModel1, bill, owns, URI + "Audi");
		tdb.addStatement(namedModel1, bill, owns, URI + "BMW");

		// named Model 2
		tdb.addStatement(namedModel2, john, owns, URI + "Chrysler");
		tdb.addStatement(namedModel2, john, owns, URI + "Ford");
		tdb.addStatement(namedModel2, bill, owns, URI + "Chevrolet");

		// null = wildcard search. Matches everything with BMW as object!
		List<Statement> result = tdb.getStatements(namedModel1, null, null, URI + "BMW");
		System.out.println(namedModel1 + " size: " + result.size() + "\n\t" + result);

		// null = wildcard search. Matches everything with john as subject!
		result = tdb.getStatements(namedModel2, john, null, null);
		System.out.println(namedModel2 + " size: " + result.size() + "\n\t" + result);

		// remove all statements from namedModel1
		tdb.removeStatement(namedModel1, john, owns, URI + "Porsche");
		tdb.removeStatement(namedModel1, john, owns, URI + "BMW");
		tdb.removeStatement(namedModel1, mike, owns, URI + "BMW");
		tdb.removeStatement(namedModel1, bill, owns, URI + "Audi");
		tdb.removeStatement(namedModel1, bill, owns, URI + "BMW");

		result = tdb.getStatements(namedModel1, john, null, null);
		System.out.println(namedModel1 + " size: " + result.size() + "\n\t" + result);
		tdb.close();
	}

}

 

 

출력 결과
Model_German_Cars size: 3
	[[https://tutorial-academy.com/2015/tdb#John, https://tutorial-academy.com/2015/tdb#owns, https://tutorial-academy.com/2015/tdb#BMW], [https://tutorial-academy.com/2015/tdb#Mike, https://tutorial-academy.com/2015/tdb#owns, https://tutorial-academy.com/2015/tdb#BMW], [https://tutorial-academy.com/2015/tdb#Bill, https://tutorial-academy.com/2015/tdb#owns, https://tutorial-academy.com/2015/tdb#BMW]]
Model_US_Cars size: 2
	[[https://tutorial-academy.com/2015/tdb#John, https://tutorial-academy.com/2015/tdb#owns, https://tutorial-academy.com/2015/tdb#Chrysler], [https://tutorial-academy.com/2015/tdb#John, https://tutorial-academy.com/2015/tdb#owns, https://tutorial-academy.com/2015/tdb#Ford]]
Model_German_Cars size: 0
	[]

 

반응형
저작자표시 변경금지 (새창열림)

'Java > RDF&Jena' 카테고리의 다른 글

[RDF4J] 설치 및 사용법  (0) 2021.05.04
[Ontology] 온톨로지란? 시맨틱 웹의 기초  (0) 2020.03.30
[Jena] Apache Jena TDB란?  (0) 2020.03.27
[RDF] Parse error: Bad character in IRI(space) 해결 방법  (0) 2020.03.27
[Jena] Apache Jena Fuseki 리눅스 설치 방법  (0) 2020.03.27
    'Java/RDF&Jena' 카테고리의 다른 글
    • [RDF4J] 설치 및 사용법
    • [Ontology] 온톨로지란? 시맨틱 웹의 기초
    • [Jena] Apache Jena TDB란?
    • [RDF] Parse error: Bad character in IRI(space) 해결 방법
    기은P
    기은P
    기은P의 블로그 일상과 개발 관련 포스팅 #React #Typescript #Next #Nest https://github.com/kimdongjang

    티스토리툴바