Spring Data JPA CRUD Example

stackchief /

Spring Data JPA CRUD example including extending the CrudRepository interface, creating, reading, updating, and deleting managed entities.

Spring Data JPA

Spring Data JPA Tutorial

Spring Data JPA Example

Spring Data JPA CRUD Example

Spring Data JPA vs Hibernate

Spring Data JPA Interview Questions

User Entity

package userservice.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class User {
    @Id
    @GeneratedValue
    private long id;

    private String name;

    public long getId(){
        return this.id;
    }

    public String getName(){
        return this.name;
    }

    public void setName(String name){
        this.name = name;
    }
}

User Repository

package userservice.repository;

import userservice.model.User;
import org.springframework.data.repository.CrudRepository;

public interface UserRepository extends CrudRepository {
}

CRUD Examples

package userservice;

import userservice.model.User;
import userservice.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Application {

    private static final Logger log =
            LoggerFactory.getLogger(Application.class);

    public static void main(String[] args){
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public CommandLineRunner demo(UserRepository repo) {
        return (args) -> {
            //CREATE
            User user = new User();
            repo.save(user);

            //READ
            User savedUser = repo.findById(user.getId()).get();

            //UPDATE
            savedUser.setName("Ted");
            repo.save(savedUser);

            //DELETE
            repo.delete(savedUser);
        };
    }
}

Your thoughts?