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
Please enter at least three characters to search
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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

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

  • DGS GraphQL and Spring Boot
  • Infrastructure as Code (IaC) Beyond the Basics
  • Blue Skies Ahead: An AI Case Study on LLM Use for a Graph Theory Related Application
  • Ethical AI in Agile
  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
Likes (1)
Comment
Save
Tweet
Share
1.4K 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
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and 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:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!