Use Hibernate with Spring Boot, Wildfly and Oracle DB - oracle

I'm trying to understand how to write a simple method to retrieve data from a DB without success.
I'm using Spring Boot 2.1, Hibernate (provided by Spring Boot), Wildfly 14 and Oracle 12.
Connection with the DB seems to work using datasources on standalone.xml (read by the application.properties file). My problem is that if I try to use EntityManager, EntityManagerFactory or Repositories they are always null and I cannot understand why.
Probably I'm missing something on the configuration. My application.properties is:
# Datasource
spring.datasource.jndi-name=java:/TestDB
# Hibernate
hibernate.dialect: org.hibernate.dialect.Oracle10gDialect
hibernate.show_sql: true
# logging
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n
logging.level.org.hibernate.SQL=debug
I defined a simple Entity like this
public class MyEntity {
#Id
#Column
private int myId;
private int anotherData;
... (getters and setters) ...
}
Now I don't know what to do.
I created a DAO class with some Autowired variables (like EntityManagerFactory) but they're always null.
How can I manipulate my entities?

I foud the solution looking at this example.

Related

#DataJpaTest loads context so fails on missing beans

Been at this for a few hours now and tried various things with no avail.
I am trying to write basic #DataJpaTest classes to test my native queries etc.
The issue is the test seems to try load the entire SpringApplication context rather than the "slice" required for the tests.
reflectoring.io - Data JPA Tests
As far as I understand, #DataJpaTest should only loads up the bare minimum beans for Entity Management, Repositories and a few other basic beans.
I am overriding the "default H2 database" it uses (as I have custom native SQL queries) so my test looks like:
#DataJpaTest
#ActiveProfiles("jpa")
#Log4j2
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class BrandServiceJpaDataTest {
#Autowired
private WebApiBrandServiceRepo brandServiceRepo;
#Autowired
private BrandRepo brandRepo;
#Test
#DisplayName("Get Brand Services from REPO")
public void getBrandServices() {
final List<BrandService> all = brandServiceRepo.findAll();
log.info(all);
}
}
Properties are simple, I was trying to use #TestContainers but would rather have this working with a basic local hosted DB:
#============ DATABASE ===========#
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/aspwtest
spring.datasource.username=dev
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
spring.jpa.show-sql=true
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = create-drop
When running the test, I can see in the logs the application context being loaded up with and leading to missing bean errors as it seems to be trying to load far too much of the context (i.e. missing RestTemplate/Validation beans etc.).
Description:
Field validator in ms.allstar.wallet.webserver.patching.EntityPatcher required a bean of type 'javax.validation.ValidatorFactory' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'javax.validation.ValidatorFactory' in your configuration.
Is there some form of config I am missing?
I know I could probably go around annotating some beans like #ActiveProfile("jpadatatest") but that feels very hacky and would sort of defeat the purpose of #DataJpaTest existing.

Read database object with spring boot and h2

I want to know how to read database object from h2 database into my spring controller using hibernate (or anything really, I am not married to hibernate).
I have a simple project setup using gradle.
And my application.properties is
spring.thymeleaf.cache=false
# Datasource
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.platform=h2
spring.datasource.url=jdbc:h2:mem:database
spring.datasource.username=something
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.show-sql=true
# H2
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false
# Hibernate
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.show_sql=false
spring.jpa.properties.hibernate.use_sql_comments=false
spring.jpa.properties.hibernate.format_sql=false
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
I can see that schema.sql and data.sql are being executed. And I see my table exists with data inside of it using h2 console. I have an entity object made too.
However I have no idea how I would go about reading my entity object from h2 and into my controller. Can someone point to the right resource or explain how to go about doing it?
By far the simplest approach to this is to use spring-data-jpa. To do this you need an entity (that is, a class with an #javax.persistence.Entity annotation) that will represent a row in your table.
#Entity
public class Thing {
#Id
private String id;
private String name;
}
Then you need a repository that can read and write from the DB. This is an interface that extends one of the spring repository classes, usually CrudRepository, like this:
public interface CustomerRepository extends CrudRepository<Thing, String> {
Thing findById(long id);
}
Then, autowire the repo into your controller's constructor, and you're nearly finished. The last part is calling one of the methods on the repo. You don't have to actually implement the repo, spring will do that for you. The base repo has plenty of useful default methods that you don't even have to list in your code. There are plenty of references for all of this on spring's website and I've linked you to a good tutorial for it (it has gradle examples, but you should really be using maven because it's a lot better in every possible respect).

Spring-boot default EntityManager

Does spring-boot have a default EntityManager. I am setting one up right now but I noticed when my project loads I see this:
LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
Is this a default EntityManager and if so, how do I access it?
Thank you in advance.
You can use the #PersistenceContext annotation to inject the entity manager into your spring beans:
#PersistenceContext
EntityManager em;
When using spring-boot-starter-data-jpa, all you need to do is configure the data source using the spring.datasource.{url, username, password, driver-class-name} properties in application.properties.
If you want to use an in-memory database like H2 for development, not even that is necessary. Just include the database as a dependency.
Once you do that, you should be able to inject the EntityManager into your beans.

SpringBoot Datasource AutoConfiguration Not Working

I have a simple SpringBoot application and I'd like to use AutoConfiguration to configure the Tomcat jdbc pooled data sources.
I am using these Spring dependencies:
// Spring Boot
compile 'org.springframework.boot:spring-boot-starter-web:1.3.5.RELEASE'
compile 'org.springframework.boot:spring-boot-starter-jdbc:1.3.5.RELEASE'
Here are my datasource properties in my application.yml file:
spring:
datasource:
url: jdbc:mysql://my.host/mydb
username: user
password: pwd
driver-class-name: com.mysql.jdbc.Driver
initialSize: 5
I am sure the properties are being loaded because the app is picking up other values.
I define the bean in my config file as:
#Bean(name="myDataSource")
#ConfigurationProperties(prefix="spring.datasource")
public DataSource getDataSource() {
DataSource dataSource = DataSourceBuilder.create().build()
return dataSource
}
And I inject the datasource into my DAO like this:
#Slf4j
#Repository
class MyDAO {
#Autowired
DataSource dataSource
public void getFoo() {
log.info("DB URL: ${dataSource.getUrl()}")
}
}
If I set a breakpoint in the getDataSource() method, the DataSourceBuilder will create an instance of DataSource. However, all the properties of that object like URL, user and password are all null. Also, when I call getFoo(), the dataSource variable is null. I have tried commenting out the bean definition in my AppConfig. The dataSource is still null. Any suggestions?
I looked through the Spring Boot documentation and my Spring book but I didn't see any examples like this. I see examples where I create the DataSource myself. But I was hoping Spring's auto-configuration would tie this stuff together automatically.
Thanks in advance for any help you can provide.
By creating your own bean, you're actually switching off Boot's auto-configuration of a DataSource. You can just delete your getDataSource method and let Boot auto-configure one instead.
Based on Andy's comments I found out that I had two problems. First of all, I needed to include the JPA dependency to the project. I added this line to my build.gradle file:
compile 'org.springframework.boot:spring-boot-starter-data-jpa:1.3.5.RELEASE'
Second, I was creating instances of MyDAO using new(). I fixed this by creating a service class that used #Autowired to inject an instance of MyDAO. Once the DAO became a Spring managed bean, it was able to inject the instance of DataSource from the Tomcat connection pool.

spring boot could show sql even use JdbcTemplate directly

spring boot project, used JdbcTemplate, and want to show sql which is executed, the configuration is as below
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
but nothing output, it seems above configuration only support spring data jpa, So I'd like to know does exist some manner could show sql even used JdbcTemplate directly?
There is a reason why the property is named spring.jpa something: it is to indicate you that it relates to JPA in some form.
If you're using JdbcTemplate, you're not using JPA hence that property can't have any effect. You can enable logging for the org.springframework.jdbc.core.JdbcTemplate class
logging.level.org.springframework.jdbc.core.JdbcTemplate=debug

Resources