DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Apache Cassandra Horizontal Scalability for Java Applications [Book]
  • 5 Key Postgres Advantages Over MySQL
  • Database Bottlenecks Nobody Talks About: Optimizing SQL Queries Beyond Indexing
  • Seeding Postgres When Your Schema Has Foreign-Key Cycles

Trending

  • Two Engines, One Query: DuckDB Inside Neo4j
  • PostgreSQL vs Oracle: When Higher Cost Means Better Performance
  • Idempotency Under Concurrency: Why Your Application Check Isn't the Last Line of Defense
  • Why Spark Executors Leave Cores Idle on YARN: A Packing Model for Executor Sizing

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Frameworks
  4. Using Schema Annotations to Create and Execute SQL Queries

Using Schema Annotations to Create and Execute SQL Queries

See how schema annotations and QueryBuilder can be used to simplify the creation and execution of native SQL queries in Java.

By 
Greg Brown
·
May. 23, 24 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
2.2K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Kilo is an open-source framework for creating and consuming RESTful and REST-like web services in Java. Because many web services provide access to data stored in relational databases, Kilo includes support for programmatically constructing and executing SQL queries via the QueryBuilder class.

For example, given the following tables (adapted from the MySQL tutorial):

SQL
 
create table owner (
    name varchar(20),
    primary key (name)
);
SQL
 
create table pet (
    name varchar(20),
    owner varchar(20),
    species varchar(20),
    sex char(1),
    birth date,
    death date,
    primary key (name),
    foreign key (owner) references owner(name)
);


This code could be used to create a query that returns all rows associated with a particular owner:

Java
 
var queryBuilder = new QueryBuilder();

queryBuilder.appendLine("select * from pet where owner = :owner order by name");


The colon character identifies “owner” as a parameter, or variable. Parameter values, or arguments, can be passed to QueryBuilder’s executeQuery() method as shown below:

Java
 
try (var statement = queryBuilder.prepare(getConnection());
    var results = queryBuilder.executeQuery(statement, mapOf(
        entry("owner", owner)
    ))) {
    ...
}


The ResultSetAdapter type returned by executeQuery() provides access to the contents of a JDBC result set via the Iterable interface. Individual rows are represented by Map instances produced by the adapter’s iterator. The results could be coerced to a list of Pet instances and returned to the caller, or used as the data dictionary for a template document:

Java
 
return results.stream().map(result -> BeanAdapter.coerce(result, Pet.class)).toList();
Java
 
var templateEncoder = new TemplateEncoder(getClass().getResource("pets.html"), resourceBundle);

templateEncoder.write(results, response.getOutputStream());


Schema Annotations

Earlier Kilo versions supported query construction using “schema types,” enums that provided a SQL-like DSL in Java code. However, these ultimately proved too cumbersome for practical use and were abandoned in favor of “schema annotations.”

For example, given these type definitions:

Java
 
@Table("owner")
public interface Owner {
    @Column("name")
    @PrimaryKey
    @Index
    String getName();
}
Java
 
@Table("pet")
public interface Pet {
    @Column("name")
    @PrimaryKey
    @Index
    String getName();
    @Column("owner")
    @ForeignKey(Owner.class)
    String getOwner();
    @Column("species")
    String getSpecies();
    @Column("sex")
    String getSex();
    @Column("birth")
    LocalDate getBirth();
    @Column("death")
    LocalDate getDeath();
}


The preceding query could be written as follows:

Java
 
var queryBuilder = QueryBuilder.select(Pet.class).filterByForeignKey(Owner.class, "owner").ordered(true);


The Table annotation associates an entity type with a database table. Similarly, the Column annotation associates a property with a column in the table. The PrimaryKey annotation indicates that a property represents the table’s primary key. The ForeignKey annotation indicates that a property represents a relationship to another table. Finally, the Index annotation indicates that a property is part of the default sort order for an entity.

While schema annotations may seem similar to JPA, the two serve different purposes. JPA is a heavyweight abstraction designed to hide the details of database access from the developer, whereas schema annotations are simply meant to help simplify the task of writing native SQL queries.

Insert, update, and delete operations are also supported. See the project README or the pet and catalog service examples for more information.

Database Relational database sql Open source Framework

Published at DZone with permission of Greg Brown. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Apache Cassandra Horizontal Scalability for Java Applications [Book]
  • 5 Key Postgres Advantages Over MySQL
  • Database Bottlenecks Nobody Talks About: Optimizing SQL Queries Beyond Indexing
  • Seeding Postgres When Your Schema Has Foreign-Key Cycles

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook