Use Agtype in Java with JDBC
masterTo work with Apache AGE graph data in Java, you must register the agtype data type with your PgConnection. This allows you to map AGE-specific types to the org.apache.age.jdbc.base.Agtype class.
Steps to integrate:
- Connect to PostgreSQL using the standard JDBC driver.
- Unwrap the connection to a
PgConnectionobject. - Call
connection.addDataType("agtype", Agtype.class). - Configure the AGE extension by executing
CREATE EXTENSION IF NOT EXISTS age;,LOAD 'age', and setting thesearch_pathtoag_catalog, "$user", public;. - Execute Cypher queries using the
cypher()function and cast results toagtype. - Retrieve results using
rs.getObject(index, Agtype.class).
import org.apache.age.jdbc.base.Agtype;
import org.postgresql.jdbc.PgConnection;
import java.sql.*;
public class Sample {
static final String DB_URL = "jdbc:postgresql://localhost:5432/demo";
static final String USER = "postgres";
static final String PASS = "pass";
public static void main(String[] args) {
// Open a connection
try {
PgConnection connection = DriverManager.getConnection(DB_URL, USER, PASS).unwrap(PgConnection.class);
connection.addDataType("agtype", Agtype.class);
// configure AGE
Statement stmt = connection.createStatement();
stmt.execute("CREATE EXTENSION IF NOT EXISTS age;");
stmt.execute("LOAD 'age'");
stmt.execute("SET search_path = ag_catalog, \"$user\", public;");
// Run cypher
ResultSet rs = stmt.executeQuery("SELECT * from cypher('demo_graph', $$ MATCH (n) RETURN n $$) as (n agtype);");
while (rs.next()) {
// Returning Result as Agtype
Agtype returnedAgtype = rs.getObject(1, Agtype.class);
String nodeLabel = returnedAgtype.getMap().getObject("label").toString();
String nodeProp = returnedAgtype.getMap().getObject("properties").toString();
System.out.println("Vertex : " + nodeLabel + ", \tProps : " + nodeProp);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}