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
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

DZone Security Research: Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns: Explore key traits of migrating open-source software and its impact on software development.

Related

  • Apache Cassandra Horizontal Scalability for Java Applications [Book]
  • 5 Key Postgres Advantages Over MySQL
  • Basic CRUD Operations Using Hasura GraphQL With Distributed SQL on GKE
  • RION - A Fast, Compact, Versatile Data Format

Trending

  • Building an Effective Zero Trust Security Strategy for End-To-End Cyber Risk Management
  • Operational Excellence Best Practices
  • GBase 8a Implementation Guide: Resource Assessment
  • A Complete Guide To Implementing GraphQL for Java
  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 user avatar
Greg Brown
·
May. 23, 24 · Tutorial
Like (1)
Save
Tweet
Share
943 Views

Join the DZone community and get the full member experience.

Join For Free

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, DZone MVB. 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
  • Basic CRUD Operations Using Hasura GraphQL With Distributed SQL on GKE
  • RION - A Fast, Compact, Versatile Data Format

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: