Creating a simple CRUD app on Spring Boot using H2, Hibernate
Tags: java, beginners, programming
Published: 2022-12-12 20:48:30

**Introduction**

Creating a CRUD (Create, Read, Update, Delete) application on Spring Boot using H2, Hibernate is a great way to quickly develop a powerful and efficient web application. In this tutorial, we will walk through the steps of creating a simple CRUD application on Spring Boot using H2, Hibernate. 

**Prerequisites**

Before starting this tutorial, you should have the following installed: 

- Java 8 or higher
- Apache Maven 3.x
- Eclipse IDE 

You should also have a basic understanding of the Spring Boot framework and the H2 and Hibernate databases. 

**Step 1: Create a Spring Boot Project**

The first step to creating a CRUD application on Spring Boot using H2, Hibernate is to create a Spring Boot project. To do this, open the Eclipse IDE and select “File > New > Spring Starter Project” from the menu bar. 

In the next window, enter a project name, choose the language as Java, and select the Spring Boot version. Then, click “Next”.

On the next screen, select the dependencies for your project. For this tutorial, we will choose “Web”, “H2 Database”, and “JPA (Hibernate)”. Click “Finish” to create the project. 

**Step 2: Create the Database Tables**

Now that we have our project created, we need to create the database tables. To do this, open the “application.properties” file located in the “src/main/resources” folder. 

In this file, we will set the database URL, username, and password. For this tutorial, we will use “jdbc:h2:mem:testdb” as the database URL. Set the username and password as “sa”. 

Next, we will create the database tables. To do this, create a new file called “schema.sql” in the “src/main/resources” folder. In this file, we will write the SQL code to create the database tables. For example:

```
CREATE TABLE users ( 
  id INTEGER PRIMARY KEY, 
  name VARCHAR(255), 
  email VARCHAR(255)
);

CREATE TABLE posts ( 
  id INTEGER PRIMARY KEY, 
  title VARCHAR(255), 
  content VARCHAR(255)
);
```

**Step 3: Create the Entity Classes**

The next step is to create the entity classes. These classes will be used to map the database tables to Java objects. 

Create a new package called “entities” in the “src/main/java” folder. In this package, create two classes called “User” and “Post”. 

For the User class, add the following code: 

```
@Entity
public class User {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  private String name;
  private String email;

  // Getters and setters

}
```

For the Post class, add the following code:

```
@Entity
public class Post {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  private String title;
  private String content;

  // Getters and setters

}
```

**Step 4: Create the Repository Classes**

The next step is to create the repository classes. These classes will be used to access the database and perform CRUD operations. 

Create a new package called “repositories” in the “src/main/java” folder. In this package, create two classes called “UserRepository” and “PostRepository”. 

For the UserRepository class, add the following code: 

```
@Repository
public interface UserRepository extends JpaRepository<User, Long> {

}

```
For the PostRepository class, add the following code:

```
@Repository
public interface PostRepository extends JpaRepository<Post, Long> {

}
```

**Step 5: Create the Service Classes**

The next step is to create the service classes. These classes will be used to manage the data and perform operations. 

Create a new package called “services” in the “src/main/java” folder. In this package, create two classes called “UserService” and “PostService”. 

For the UserService class, add the following code: 

```
@Service
public class UserService {

  @Autowired
  private UserRepository userRepository;

  public List<User> getAllUsers() {
    return userRepository.findAll();
  }

  public User getUserById(Long id) {
    return userRepository.findById(id).get();
  }

  public User createUser(String name, String email) {
    User user = new User();
    user.setName(name);
    user.setEmail(email);
    return userRepository.save(user);
  }

  public User updateUser(Long id, String name, String email) {
    User user = userRepository.findById(id).get();
    user.setName(name);
    user.setEmail(email);
    return userRepository.save(user);
  }

  public void deleteUser(Long id) {
    userRepository.deleteById(id);
  }

}

```
For the PostService class, add the following code: 

```
@Service
public class PostService {

  @Autowired
  private PostRepository postRepository;

  public List<Post> getAllPosts() {
    return postRepository.findAll();
  }

  public Post getPostById(Long id) {
    return postRepository.findById(id).get();
  }

  public Post createPost(String title, String content) {
    Post post = new Post();
    post.setTitle(title);
    post.setContent(content);
    return postRepository.save(post);
  }

  public Post updatePost(Long id, String title, String content) {
    Post post = postRepository.findById(id).get();
    post.setTitle(title);
    post.setContent(content);
    return postRepository.save(post);
  }

  public void deletePost(Long id) {
    postRepository.deleteById(id);
  }

}
```

**Step 6: Create the Controller Classes**

The final step is to create the controller classes. These classes will be used to map the requests to the service classes. 

Create a new package called “controllers” in the “src/main/java” folder. In this package, create two classes called “UserController” and “PostController”. 

For the UserController class, add the following code: 

```
@RestController
@RequestMapping("/users")
public class UserController {

  @Autowired
  private UserService userService;

  @GetMapping
  public List<User> getAllUsers() {
    return userService.getAllUsers();
  }

  @GetMapping("/{id}")
  public User getUserById(@PathVariable Long id) {
    return userService.getUserById(id);
  }

  @PostMapping
  public User createUser(@RequestBody User user) {
    return userService.createUser(user.getName(), user.getEmail());
  }

  @PutMapping("/{id}")
  public User updateUser(@PathVariable Long id, @RequestBody User user) {
    return userService.updateUser(id, user.getName(), user.getEmail());
  }

  @DeleteMapping("/{id}")
  public void deleteUser(@PathVariable Long id) {
    userService.deleteUser(id);
  }

}
```

For the PostController class, add the following code: 



```
`@RestController
@RequestMapping("/posts")
public class PostController {

  @Autowired
  private PostService postService;

  @GetMapping
  public List<Post> getAllPosts() {
    return postService.getAllPosts();
  }

  @GetMapping("/{id}")
  public Post getPostById(@PathVariable Long id) {
    return postService.getPostById(id);
  }

  @PostMapping
  public Post createPost(@RequestBody Post post) {
    return postService.createPost(post.getTitle(), post.getContent());
  }

  @PutMapping("/{id}")
  public Post updatePost(@PathVariable Long id, @RequestBody Post post) {
    return postService.updatePost(id, post.getTitle(), post.getContent());
  }

  @DeleteMapping("/{id}")
  public void deletePost(@PathVariable Long id) {
    postService.deletePost(id);
  }

}`

```

**<u>Conclusion</u>**

In this tutorial, we have walked through the steps of creating a simple CRUD application on Spring Boot using H2, Hibernate. We have created our project, created the database tables, created the entity classes, created the repository classes, created the service classes, and created the controller classes. 

With this application, we can now easily create, read, update, and delete data using the H2 and Hibernate databases.