Integrate Spring Boot app with Postgres Database using hibernate.

Manoj Ahirwar
3 min readJan 1, 2023

--

Photo by Markus Winkler on Unsplash

Integrating a Spring Boot application with a Postgres database using Hibernate is a simple and straightforward process. Hibernate is a popular Java-based framework that simplifies the process of interacting with a database, allowing you to focus on building your application rather than dealing with low-level JDBC code.

In this article, we will see how to integrate your Spring Boot app with Postgres using Hibernate.

First, you will need to make sure that you have Postgres installed on your machine and have created a database for your application. You can do this by following the instructions for your operating system, or by using a cloud-based solution such as AWS RDS or Heroku Postgres.

Next, you will need to add the required dependencies to your Maven project. Open the pom.xml file in your project and add the following dependencies:

<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.14</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.23.Final</version>
</dependency>

Once you have the required dependencies added, you can configure the connection to your Postgres database in the application.properties file in your Spring Boot project. You will need to provide the following information:

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:postgresql://host:port/database
spring.datasource.username=your_username
spring.datasource.password=your_password

Replace host, port, database, your_username, and your_password with the appropriate values for your Postgres database. The spring.jpa.hibernate.ddl-auto property tells Hibernate to update the database schema based on your entity classes.

You can then create a data source and entity manager by adding the following to your Spring Boot application:

@Bean
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);

LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.example.app.model");
factory.setDataSource(dataSource());
return factory;
}

@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory().getObject());
return txManager;
}

Replace com.example.app.model with the package containing your JPA entities.

To use Hibernate in your application, you will need to create entity classes that represent the tables in your database. These classes should be annotated with the @Entity annotation and should have fields that correspond to the columns in your tables. You can use the @Column annotation to specify the name of the column in the database and other properties such as data type, length, and nullability.

Here is an example of a simple entity class:

@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(nullable = false, unique = true)
private String username;

@Column(nullable = false)
private String password;

// Getters and setters
}

Once you have created your entity classes, you can use the entity manager and transaction manager in your application to perform CRUD operations on your Postgres database.

For example, to save an entity to the database, you can use the following code:

@Autowired
private EntityManager entityManager;

@Autowired
private PlatformTransactionManager transactionManager;

...

TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
try {
entityManager.persist(entity);
transactionManager.commit(status);
} catch (Exception e) {
transactionManager.rollback(status);
}

To retrieve an entity from the database, you can use the find method of the entity manager:

User user = entityManager.find(User.class, id);

You can also use the Query interface to execute more complex queries and retrieve a list of results:

Query query = entityManager.createQuery("SELECT u FROM User u WHERE u.username = :username");
query.setParameter("username", "john");
List<User> users = query.getResultList();

This is just a basic example of how to integrate a Spring Boot application with a Postgres database using Hibernate. There are many other configuration options and advanced features available, but this should provide a good starting point for most applications.

--

--

No responses yet