Saturday, June 2, 2018

Spring Boot and H2

https://dzone.com/articles/spring-boot-and-spring-jdbc-with-h2

Example code is here:

https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-jdbc-with-h2

you must add spring.h2.console.path=/h2 in the application.properties file

in a nutshell:

in pom.xml

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>


<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>


in application.properties

# Datasource
#spring.datasource.url=jdbc:h2:file:~/test
spring.datasource.url=jdbc:h2:file:~/mydb
spring.datasource.username=mydb
spring.datasource.password=mydb
spring.datasource.driver-class-name=org.h2.Driver

# H2
# Enabling H2 Console
spring.h2.console.path=/h2
spring.h2.console.enabled=true
#Turn Statistics on
spring.jpa.properties.hibernate.generate_statistics=true
logging.level.org.hibernate.stat=debug
# Show all queries
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.type=trace


#spring.jpa.generate-ddl=false
spring.jpa.hibernate.ddl-auto=update
#spring.jpa.hibernate.ddl-auto=validate


To implement a repository:


import org.springframework.data.repository.CrudRepository;

public interface QuarantineRepository extends CrudRepository<Quarantine, Long> {
List findBygav(String gav);

}


To use the repository in a @javax.inject.Named bean:

import javax.inject.Inject;
...

@Inject
QuarantineRepository quarantineRepository ;


where Quarantine is like this:


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

@Entity
public class Quarantine {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String gav;

etc etc

}



No comments: