Convert Figma logo to code with AI

spring-projects logospring-data-jpa

Simplifies the development of creating a JPA-based data access layer.

2,975
1,407
2,975
155

Top Related Projects

IntelliJ IDEA Community Edition & IntelliJ Platform

Hibernate's core Object/Relational Mapping functionality

Unified Queries for Java

6,093

jOOQ is the best way to write SQL in Java

19,687

MyBatis SQL mapper framework for Java

Quick Overview

Spring Data JPA is a project within the Spring Data family that simplifies the development of Java Persistence API (JPA) based data access layers. It provides a powerful repository and custom object-mapping abstractions, reducing boilerplate code and offering advanced querying capabilities.

Pros

  • Simplifies data access layer implementation with minimal configuration
  • Provides powerful query methods and dynamic query generation
  • Integrates seamlessly with other Spring Framework modules
  • Supports multiple database providers and JPA implementations

Cons

  • Learning curve for developers new to Spring ecosystem
  • Can be overkill for simple projects with basic database operations
  • Performance overhead for complex queries compared to native SQL
  • May lead to inefficient queries if not properly optimized

Code Examples

  1. Defining a simple repository interface:
public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByLastName(String lastName);
}

This code defines a repository interface for the User entity, extending JpaRepository to inherit CRUD operations and adding a custom method to find users by last name.

  1. Using derived query methods:
public interface ProductRepository extends JpaRepository<Product, Long> {
    List<Product> findByPriceGreaterThanAndCategoryOrderByNameAsc(BigDecimal price, String category);
}

This example demonstrates a derived query method that finds products with a price greater than a specified value, in a given category, ordered by name ascending.

  1. Using @Query annotation for custom queries:
public interface OrderRepository extends JpaRepository<Order, Long> {
    @Query("SELECT o FROM Order o WHERE o.status = :status AND o.createdDate > :date")
    List<Order> findRecentOrdersByStatus(@Param("status") String status, @Param("date") LocalDateTime date);
}

This code shows how to use the @Query annotation to define a custom JPQL query with named parameters.

Getting Started

To start using Spring Data JPA in your project:

  1. Add the dependency to your Maven pom.xml:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
  1. Configure your database connection in application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=user
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
  1. Create an entity class and a repository interface:
@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    // getters and setters
}

public interface UserRepository extends JpaRepository<User, Long> {
}
  1. Inject and use the repository in your service or controller:
@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public User saveUser(User user) {
        return userRepository.save(user);
    }
}

Competitor Comparisons

IntelliJ IDEA Community Edition & IntelliJ Platform

Pros of intellij-community

  • Larger and more active community, with over 13,000 stars and 5,000 forks
  • Comprehensive IDE functionality, covering a wide range of programming languages and frameworks
  • Extensive plugin ecosystem, allowing for customization and extended functionality

Cons of intellij-community

  • Significantly larger codebase, which may be more challenging to navigate and contribute to
  • Steeper learning curve for new contributors due to the complexity of the project
  • Requires more system resources to run and develop

Code Comparison

intellij-community (Java):

public class PsiJavaFileImpl extends PsiJavaFileBaseImpl implements PsiJavaFile {
  @Override
  public PsiElement setName(@NotNull String name) throws IncorrectOperationException {
    checkSetName(name);
    return super.setName(name);
  }
}

spring-data-jpa (Java):

public class SimpleJpaRepository<T, ID> implements JpaRepository<T, ID> {
  @Transactional
  @Override
  public <S extends T> S save(S entity) {
    return entityManager.merge(entity);
  }
}

Both repositories showcase Java code, but intellij-community focuses on IDE functionality, while spring-data-jpa emphasizes database operations and ORM.

Hibernate's core Object/Relational Mapping functionality

Pros of Hibernate ORM

  • More flexible and powerful, offering advanced features like caching, lazy loading, and custom SQL queries
  • Provides a complete ORM solution with its own API, allowing for more control over database operations
  • Supports a wider range of databases and can be used independently of Spring

Cons of Hibernate ORM

  • Steeper learning curve due to its complexity and extensive feature set
  • Can be overkill for simple projects, potentially leading to performance overhead
  • Requires more manual configuration compared to Spring Data JPA's convention-over-configuration approach

Code Comparison

Spring Data JPA:

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByLastName(String lastName);
}

Hibernate ORM:

Session session = sessionFactory.getCurrentSession();
List<User> users = session.createQuery("FROM User WHERE lastName = :lastName", User.class)
    .setParameter("lastName", lastName)
    .getResultList();

Spring Data JPA simplifies data access with its repository abstraction, while Hibernate ORM provides more control over query execution. Spring Data JPA builds on top of JPA (which Hibernate implements), offering a higher level of abstraction for common database operations.

Unified Queries for Java

Pros of Querydsl

  • Type-safe query construction, reducing runtime errors
  • Supports multiple backends (JPA, MongoDB, SQL)
  • More flexible and powerful querying capabilities

Cons of Querydsl

  • Steeper learning curve compared to Spring Data JPA
  • Requires additional setup and code generation
  • Less integrated with Spring ecosystem

Code Comparison

Spring Data JPA:

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByAgeGreaterThanAndNameLike(int age, String name);
}

Querydsl:

QUser user = QUser.user;
List<User> users = queryFactory.selectFrom(user)
    .where(user.age.gt(age).and(user.name.like(name)))
    .fetch();

Spring Data JPA offers a more concise and declarative approach, while Querydsl provides greater flexibility and type-safety at the cost of verbosity. Spring Data JPA is more tightly integrated with the Spring ecosystem, making it easier to use in Spring-based applications. Querydsl, on the other hand, offers more powerful querying capabilities and supports multiple backends, making it a versatile choice for complex querying needs across different data stores.

6,093

jOOQ is the best way to write SQL in Java

Pros of jOOQ

  • Type-safe SQL queries with compile-time checking
  • Supports a wide range of databases and SQL dialects
  • Powerful code generation for database schema

Cons of jOOQ

  • Steeper learning curve compared to Spring Data JPA
  • Requires more boilerplate code for simple CRUD operations
  • Less abstraction from the underlying database

Code Comparison

Spring Data JPA:

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByLastName(String lastName);
}

jOOQ:

DSLContext create = DSL.using(connection, SQLDialect.MYSQL);
Result<Record> result = create.select()
    .from(USER)
    .where(USER.LAST_NAME.eq("Smith"))
    .fetch();

Spring Data JPA offers a more declarative approach with less code for basic operations, while jOOQ provides more control and type-safety for complex queries. jOOQ excels in scenarios requiring advanced SQL features, while Spring Data JPA is often preferred for its simplicity and integration with the Spring ecosystem.

19,687

MyBatis SQL mapper framework for Java

Pros of MyBatis-3

  • More control over SQL queries, allowing for complex and optimized database operations
  • Simpler learning curve for developers familiar with SQL
  • Better performance for complex queries and large datasets

Cons of MyBatis-3

  • More verbose and requires more manual configuration
  • Less abstraction from the database, potentially leading to tighter coupling
  • Lacks some of the advanced features and conveniences provided by Spring Data JPA

Code Comparison

MyBatis-3:

<select id="findUserById" resultType="User">
  SELECT * FROM users WHERE id = #{id}
</select>

Spring Data JPA:

public interface UserRepository extends JpaRepository<User, Long> {
  User findById(Long id);
}

MyBatis-3 requires explicit SQL queries in XML or annotations, while Spring Data JPA generates queries based on method names. Spring Data JPA offers a higher level of abstraction, reducing boilerplate code and providing more built-in functionality. However, MyBatis-3 gives developers more control over the exact SQL being executed, which can be beneficial for complex queries or performance optimization.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

= Spring Data JPA image:https://jenkins.spring.io/buildStatus/icon?job=spring-data-jpa%2Fmain&subject=Build[link=https://jenkins.spring.io/view/SpringData/job/spring-data-jpa/] https://gitter.im/spring-projects/spring-data[image:https://badges.gitter.im/spring-projects/spring-data.svg[Gitter]] image:https://img.shields.io/badge/Revved%20up%20by-Develocity-06A0CE?logo=Gradle&labelColor=02303A["Revved up by Develocity", link="https://ge.spring.io/scans?search.rootProjectNames=Spring Data JPA Parent"]

Spring Data JPA, part of the larger https://projects.spring.io/spring-data[Spring Data] family, makes it easy to implement JPA-based repositories. This module deals with enhanced support for JPA-based data access layers. It makes it easier to build Spring-powered applications that use data access technologies.

Implementing a data access layer of an application has been cumbersome for quite a while. Too much boilerplate code has to be written to execute simple queries as well as perform pagination, and auditing. Spring Data JPA aims to significantly improve the implementation of data access layers by reducing the effort to the amount that’s actually needed. As a developer you write your repository interfaces, including custom finder methods, and Spring will provide the implementation automatically.

== Features

  • Implementation of CRUD methods for JPA Entities
  • Dynamic query generation from query method names
  • Transparent triggering of JPA NamedQueries by query methods
  • Implementation domain base classes providing basic properties
  • Support for transparent auditing (created, last changed)
  • Possibility to integrate custom repository code
  • Easy Spring integration with custom namespace

== Code of Conduct

This project is governed by the https://github.com/spring-projects/.github/blob/e3cc2ff230d8f1dca06535aa6b5a4a23815861d4/CODE_OF_CONDUCT.md[Spring Code of Conduct]. By participating, you are expected to uphold this code of conduct. Please report unacceptable behavior to spring-code-of-conduct@pivotal.io.

== Getting Started

Here is a quick teaser of an application using Spring Data Repositories in Java:

[source,java]

public interface PersonRepository extends CrudRepository<Person, Long> {

List findByLastname(String lastname);

List findByFirstnameLike(String firstname); }

@Service public class MyService {

private final PersonRepository repository;

public MyService(PersonRepository repository) { this.repository = repository; }

public void doWork() {

repository.deleteAll();

Person person = new Person();
person.setFirstname("Oliver");
person.setLastname("Gierke");
repository.save(person);

List<Person> lastNameResults = repository.findByLastname("Gierke");
List<Person> firstNameResults = repository.findByFirstnameLike("Oli%");

} }

@Configuration @EnableJpaRepositories("com.acme.repositories") class AppConfig {

@Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build(); }

@Bean public JpaTransactionManager transactionManager(EntityManagerFactory emf) { return new JpaTransactionManager(emf); }

@Bean public JpaVendorAdapter jpaVendorAdapter() { HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter(); jpaVendorAdapter.setDatabase(Database.H2); jpaVendorAdapter.setGenerateDdl(true); return jpaVendorAdapter; }

@Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean lemfb = new LocalContainerEntityManagerFactoryBean(); lemfb.setDataSource(dataSource()); lemfb.setJpaVendorAdapter(jpaVendorAdapter()); lemfb.setPackagesToScan("com.acme"); return lemfb; } }

=== Maven configuration

Add the Maven dependency:

[source,xml]

org.springframework.data spring-data-jpa ${version} ----

If you'd rather like the latest snapshots of the upcoming major version, use our Maven snapshot repository and declare the appropriate dependency version.

[source,xml]

org.springframework.data spring-data-jpa ${version}-SNAPSHOT spring-snapshot Spring Snapshot Repository https://repo.spring.io/snapshot ----

== Getting Help

Having trouble with Spring Data? We’d love to help!

== Reporting Issues

Spring Data uses GitHub as issue tracking system to record bugs and feature requests. If you want to raise an issue, please follow the recommendations below:

== Building from Source

You don’t need to build from source to use Spring Data (binaries in https://repo.spring.io[repo.spring.io]), but if you want to try out the latest and greatest, Spring Data can be easily built with the https://github.com/takari/maven-wrapper[maven wrapper]. You also need JDK 17 or above.

[source,bash]

$ ./mvnw clean install

If you want to build with the regular mvn command, you will need https://maven.apache.org/run-maven/index.html[Maven v3.8.0 or above].

Also see link:CONTRIBUTING.adoc[CONTRIBUTING.adoc] if you wish to submit pull requests, and in particular please sign the https://cla.pivotal.io/sign/spring[Contributor’s Agreement] before your first non-trivial change.

=== Building reference documentation

Building the documentation builds also the project without running tests.

[source,bash]

$ ./mvnw clean install -Pantora

The generated documentation is available from target/antora/site/index.html.

== Guides

The https://spring.io/[spring.io] site contains several guides that show how to use Spring Data step-by-step:

== Examples

== License

Spring Data JPA is Open Source software released under the https://www.apache.org/licenses/LICENSE-2.0.html[Apache 2.0 license].