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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

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

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Spring Data JPA - Part 1
  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • The Generic Way To Convert Between Java and PostgreSQL Enums
  • Projections/DTOs in Spring Data R2DBC

Trending

  • Unlocking Data with Language: Real-World Applications of Text-to-SQL Interfaces
  • Comprehensive Guide to Property-Based Testing in Go: Principles and Implementation
  • Concourse CI/CD Pipeline: Webhook Triggers
  • Medallion Architecture: Why You Need It and How To Implement It With ClickHouse
  1. DZone
  2. Data Engineering
  3. Databases
  4. What Java DAO Layer Is Best for Your Project

What Java DAO Layer Is Best for Your Project

Reviewing and comparing the most popular java database access frameworks.

By 
Dmitry Egorov user avatar
Dmitry Egorov
DZone Core CORE ·
May. 18, 20 · Review
Likes (12)
Comment
Save
Tweet
Share
32.5K Views

Join the DZone community and get the full member experience.

Join For Free

There are many ways how to connect your Java application to a database. Here, I explain which framework is best suited to the requirements of your project.

Comparable Technologies

  • JDBC (Java database connectivity).
  • JOOQ (Java Object Oriented Querying).
  • MyBatis.
  • Hibernate.
  • Spring Data.

JDBC: Simple Database Querying

The simplest way to get data is to use provided by java api also know as Java Database Connectivity (JDBC). Provided api returns result set for given sql query:

Java
xxxxxxxxxx
1
 
1
ResultSet rs = stmt.executeQuery("SELECT id, name FROM Employees");
2
while(rs.hasNext()){
3
 log.info("Employee id: " + rs.getInt("id") + " has name: " + rs.getString("name"));
4
}


When it's better to use JDBC solution When it's better avoid JDBC solution
If  you don't want to learn any framework If you don't want to write a lot of code
If you want to have lightweight solution If you are going to migrate from one database to another
If you need custom queering 
If you need to write once and forget about it


Tip: In order to reduce a lot of  boilerplate code, I recommend using jdbc-template tools, like Spring JDBC template or Apache DBUtils. For example, in that request, the Spring template sends a request with parameters, deserialize data, close connection. This all happens in just one line: 

Java
xxxxxxxxxx
1
 
1
User user = jdbc.qeuryForObject("SELECT * FROM USERS WHERE ID = ?", 1, User.class);


JOOQ: Java Object-Oriented Querying

JOOQ framework provides a language based on generated entities. Using this language, you can create compile-time-safe queries. JOOQ can generate dialects for many databases. Also, it clean up boilerplate code, like closing connections, etc.

Java
xxxxxxxxxx
1
 
1
UserRecord user = new UserRecord();
2
user.setId(1);
3
user.setName("Peter");
4
5
Result<UserRecord> books1 = DSL.using(configuration)
6
   .selectFrom(USERS)
7
   .where(condition(user))
8
   .fetch();


When it's better to use JOOQ solution Why JOOQ is not the best option
When you need JDBC calls with compile time safe query Many features and dialects are paid
When you need to migrate JDBC dialect
When you need generated CRUD JDBC api

MyBatis: Simple ORM With Querying Support

Object relation mapping or ORM provides another way to communicate with database. The idea is to create mapping between Java objects (entities) and their corresponding tables in the database. One ORM provider is the MyBatis framework. 

MyBatis is a lightweight framework that creates mapping between entites and tables using queries (not bean structures, as it's done in JPA providers, like Hibernate). So, this framework uses queries and provides ORM features. Here, you can see a short example (without a config file):

Java
xxxxxxxxxx
1
 
1
// Bean mapping
2
public interface BlogMapper {
3
  @Select("SELECT * FROM blog WHERE id = #{id}")
4
  Blog selectBlog(int id);
5
}
6
// Fetching data
7
BlogMapper mapper = session.getMapper(BlogMapper.class);
8
Blog blog = mapper.selectBlog(101);


When it's better to use MyBatis When it's better to avoid MyBatis
When you need query flexibility in ORM When you don't like xml based logic
When you need lightweight ORM

Hibernate and Spring Data 

Both technologies support JPA (Java Persistence API). That means that both solutions can be deployed to application servers. JPA standards require mappings between tables/columns and Java objects (entites). For example, a USERS table can be mapped to the following entity:

Java
xxxxxxxxxx
1
10
 
1
@Data // this is not hibernate annotation, it's lombok getter/setter generator
2
@Entity
3
@Table(name = "USERS")
4
public class User {
5
    @Id
6
    @Column(name = "id")
7
    private Integer id;  
8
    @Column(name = "name")
9
    private String name;
10
}

Hibernate

This is the most popular ORM framework with numerous built-in features. It was first released almost 20 years ago. Hibernate also supports HQL language for custom SQL queries. 

Java
xxxxxxxxxx
1
 
1
Session session = sessionFactory.openSession();
2
User oldUser  = (User) session.get(User.class, 1); //get user
3
User newUser = new User(123,"John");
4
session.save(developer); //add user
5
//HQL example
6
Query query = session.createQuery("FROM Users");
7
List users = query.list();


When it's better to use Hibernate When it's better avoid Hibernate
When you need prototype something quickly When you don't want to generate extra java classes - entities
When you need to have built in cache When you don't want to learn one more framework
When you need to use many different databases When you don't want to lose database control
When you need to have access to complex schema structure

Spring Data or New Level of ORM Abstraction

On top of JPA entites, Spring Data provides a rich CRUD API, as well as expression query language. The key advantage of Spring data is that it requires only 2-3 lines of implementation. The generated API is based on method naming conversions. 

Java
x
11
 
1
//Implementation, just by extending CrudRepository interface
2
public interface UserRepository extends CrudRepository<User, Long> {
3
  User findByName(String name);
4
  User findById(long id);
5
  @Query("SELECT u.ID FROM USERS u WHERE like ?1") //custom expression
6
  List<Integer> findByUserName(String name);
7
}
8
//It's how to use this repository:
9
User johnUser = userRepository.findByName("John");
10
User johnUser = userRepository.findById(id);
11
List<Integer> usersIdsWithOVPostfix = userRepository.findByUserName("%OV%");


When it's better to use Spring Data When it's better avoid Spring Data
When you need prototype something quickly When you don't want to generate extra java classes - entities
When you need to use many different databases When you don't want to lose database control

Final Comparison

It is very difficult to give an objective comparative assessment. Below, I give a comparison, which is my personal opinion, and does not claim the absolute truth.


JDBC JOOQ MyBatis Hibernate Spring Data
Transparency HIGH HIGH MEDIUM LOW LOW
Query flexibility HIGH
HIGH
MEDIUM LOW LOW
Development Speed For regular queries LOW MEDIUM MEDIUM
HIGH
HIGH
Development Speed For custom queries
LOW LOW
MEDIUM
MEDIUM
MEDIUM
Migration to different DB cost HIGH LOW HIGH LOW LOW
Configuration costs LOW MEDIUM HIGH HIGH
MEDIUM


Database Java (programming language) Decentralized autonomous organization Spring Data Spring Framework Data (computing) IT Framework

Opinions expressed by DZone contributors are their own.

Related

  • Spring Data JPA - Part 1
  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • The Generic Way To Convert Between Java and PostgreSQL Enums
  • Projections/DTOs in Spring Data R2DBC

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!