spring h2 database example

To set up a Spring application with H2 database, follow these steps:

  1. Add H2 dependency: Include the H2 database dependency in your project's build file. For Maven, add the following dependency to your pom.xml file:

Replace "VERSION" with the appropriate version of the H2 database.

  1. Configure H2 database properties: In your application.properties or application.yml file, add the following configuration for H2 database:

This configuration sets up an in-memory H2 database with the JDBC URL "jdbc:h2:mem:testdb" and the default username "sa" with no password.

  1. Create database schema: Define your database schema using SQL scripts or use JPA annotations to generate the schema. For example, you can create an entity class and annotate it with @Entity, @Table, and @Column annotations to define the table structure.

  2. Access the database: Use JPA or JDBC to access the H2 database and perform CRUD operations. You can create repositories or DAO classes to handle database operations. For JPA, you can define repositories by extending the JpaRepository interface, and for JDBC, you can use the JdbcTemplate class to execute SQL queries.

  3. Test the application: Run your Spring application and test the database connectivity and functionality. You can use JUnit or other testing frameworks to write unit or integration tests for your database operations.

Remember to properly handle any exceptions and close database connections to ensure efficient and secure database interactions.

That's it! You now have a Spring application set up with the H2 database. Feel free to explore more advanced features and configurations based on your application requirements.