I want to configure 2nd level hibernate cache at Spring Boot microservice.
And I don't want to use xml at all.
Next is my example.
UserEntity.java
#Entity
#Table(name = "users")
#Cacheable
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "users")
public class UserEntity {
#Id
private long id;
#Column
private String name;
public UserEntity(long id, String name) {
this.id = id;
this.name = name;
}
// ... geters&setters
}
CacheConfig.java
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.store.MemoryStoreEvictionPolicy;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
#EnableCaching
public class CacheConfig {
#Bean
public org.springframework.cache.CacheManager cacheManager() {
return new EhCacheCacheManager(ehCacheManager());
}
private net.sf.ehcache.CacheManager ehCacheManager() {
CacheConfiguration usersCacheConfiguration = new CacheConfiguration();
usersCacheConfiguration.setName("users");
usersCacheConfiguration.eternal(false);
usersCacheConfiguration.setMaxEntriesInCache(1000);
usersCacheConfiguration.setMaxEntriesLocalDisk(0);
usersCacheConfiguration.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU);
net.sf.ehcache.config.Configuration config = new net.sf.ehcache.config.Configuration();
config.addCache(usersCacheConfiguration);
return net.sf.ehcache.CacheManager.create(config);
}
}
App.java
#SpringBootApplication
public class App {
public static void main(String[] args) {
new SpringApplicationBuilder(App.class)
.sources(CacheConfig.class)
.run(args);
}
}
application.properties
spring:
datasource:
url: jdbc:postgresql://localhost:5432/test
username: postgres
password: postgres
type: com.zaxxer.hikari.HikariDataSource
driverClassName: org.postgresql.Driver
jpa.hibernate.ddl-auto: update
jpa.open-in-view: false
jpa.properties.javax.persistence.sharedCache.mode: ALL
jpa.properties.hibernate:
dialect: org.hibernate.dialect.PostgreSQL9Dialect
jdbc.batch_size: 100
temp.use_jdbc_metadata_defaults: false
order_inserts: true
cache:
region.factory_class: org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
#region.factory_class: org.hibernate.cache.ehcache.EhCacheRegionFactory
#region_prefix: ""
use_second_level_cache: true
cache.use_query_cache: true
provider_class: org.hibernate.cache.EhCacheProvider
build.gradle
group 'com.hibernate.cache'
version '1.0-SNAPSHOT'
apply plugin: 'java'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.0.0.RELEASE'
compile group: 'org.springframework', name: 'spring-context-support', version: '5.0.4.RELEASE'
compile group: 'org.hibernate', name: 'hibernate-ehcache', version: '5.2.14.Final'
compile group: 'org.postgresql', name: 'postgresql', version: '42.1.4'
}
When I run the program I see a couple of warnings indicating that entity cache configuration is not applied:
2018-03-04 23:29:48.723 WARN 8516 --- [ main] n.s.ehcache.config.ConfigurationFactory : No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/home/vitaly/.gradle/caches/modules-2/files-2.1/net.sf.ehcache/ehcache/2.10.3/cf74f9a4a049f181833b147a1d9aa62159c9d01d/ehcache-2.10.3.jar!/ehcache-failsafe.xml
2018-03-04 23:29:48.834 WARN 8516 --- [ main] o.h.c.e.AbstractEhcacheRegionFactory : HHH020003: Could not find a specific ehcache configuration for cache named [users]; using defaults.
Does anybody know what is wrong here?
The first warning:
2018-03-04 23:29:48.723 WARN 8516 --- [ main] n.s.ehcache.config.ConfigurationFactory : No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/home/vitaly/.gradle/caches/modules-2/files-2.1/net.sf.ehcache/ehcache/2.10.3/cf74f9a4a049f181833b147a1d9aa62159c9d01d/ehcache-2.10.3.jar!/ehcache-failsafe.xml
means that no ehcache.xml configuration was found so a default, ehcache-failsafe.xml, is used.
The second warning:
2018-03-04 23:29:48.834 WARN 8516 --- [ main] o.h.c.e.AbstractEhcacheRegionFactory : HHH020003: Could not find a specific ehcache configuration for cache named [users]; using defaults.
means that there was no configuration found for the "users" region in the cache. It is, of course, not defined in ehcache-failsafe.xml and it doesn't look like the settings in CacheConfig are being picked up - at least not by the CacheManager used by Hibernate.
It should be possible to solve both by adding an ehcache.xml to the classpath (in src/main/resources), e.g.:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.ehcache.org/ehcache.xsd"
updateCheck="true"
monitoring="autodetect"
dynamicConfig="true">
<cache name="users"
maxEntriesLocalHeap="500"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
diskExpiryThreadIntervalSeconds="1"
copyOnRead="true"
copyOnWrite="true">
<copyStrategy class="net.sf.ehcache.store.compound.ReadWriteSerializationCopyStrategy" />
</cache>
</ehcache>
(see this ehcache.xml sample for more options)
And adding the following to application.yml:
spring:
cache:
ehcache:
config: classpath:ehcache.xml
A year late but the answer to your question might require you to implement your own RegionFactory class (by extending SingletonEhCacheRegionFactory) And then set your newly created class as the factory that hibernate should use: spring.jpa.properties.hibernate.cache.region.factory_class=com.my.class
https://stackoverflow.com/a/28594371/708854
Related
I have upgraded our app from springboot 2.1.4.Release to 2.5.0 and updated relevant jars for running the application. But when I am trying to deploy and run the app in aws ECS , it is giving the following error.
But when I deploy the earlier commit it is able to deploy fine.
It is not able to read the aws Secrets manager to read the values from there.
On looking carefully, I found theres a difference in startup of the springboot. If anyone can point in the right direction, it will be of great help.
The error in the aws ECS logs:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'cloudPlatformSecuirtyResourceServerConfig': Unsatisfied dependency expressed through field 'uaaResourceInfo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'UAAResourceInfoConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'moa.aws.secrets.uaa.clientId' in value "${moa.aws.secrets.uaa.clientId}"
The failed startup log for the springboot is:
2021-08-24T18:24:42.232-04:00
' |____| .__|_| |_|_| |_\__, | / / / /
2021-08-24T18:24:42.232-04:00
=========|_|==============|___/=/_/_/_/
2021-08-24T18:24:42.236-04:00
:: Spring Boot :: (v2.5.0)
2021-08-24T18:24:42.854-04:00
2021-08-24 22:24:42 [main] INFO c.g.d.o.m.MoaApplication.logStarting - Starting MoaApplication using Java 1.8.0_212 on ip-10-228-213-136.ec2.internal with PID 1 (/app/bin/app.jar started by appuser in /app/bin)
2021-08-24T18:24:42.855-04:00
2021-08-24 22:24:42 [main] INFO c.g.d.o.m.MoaApplication.logStartupProfileInfo - The following profiles are active: aws,security
2021-08-24T18:24:50.749-04:00
2021-08-24 22:24:50 [main] INFO o.s.d.r.c.RepositoryConfigurationDelegate.registerRepositoriesIn - Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-08-24T18:24:52.715-04:00
2021-08-24 22:24:52 [main] INFO o.s.d.r.c.RepositoryConfigurationDelegate.registerRepositoriesIn - Finished Spring Data repository scanning in 1900 ms. Found 29 JPA repository interfaces.
2021-08-24T18:24:53.919-04:00
2021-08-24 22:24:53 [main] INFO o.s.c.c.s.GenericScope.setSerializationId - BeanFactory id=ac4ea7b8-8e46-3560-bd24-f258beed7bb3
2021-08-24T18:24:54.857-04:00
2021-08-24 22:24:54 [main] INFO o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker.postProcessAfterInitialization - Bean 'org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration' of type [org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2021-08-24T18:24:54.860-04:00
2021-08-24 22:24:54 [main] INFO o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker.postProcessAfterInitialization - Bean 'stringOrNumberMigrationVersionConverter' of type [org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration$StringOrNumberToMigrationVersionConverter] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2021-08-24T18:24:54.914-04:00
2021-08-24 22:24:54 [main] INFO o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker.postProcessAfterInitialization - Bean 'management.metrics-org.springframework.boot.actuate.autoconfigure.metrics.MetricsProperties' of type [org.springframework.boot.actuate.autoconfigure.metrics.MetricsProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2021-08-24T18:24:54.915-04:00
2021-08-24 22:24:54 [main] INFO o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker.postProcessAfterInitialization - Bean 'org.springframework.boot.actuate.autoconfigure.metrics.data.RepositoryMetricsAutoConfiguration' of type [org.springframework.boot.actuate.autoconfigure.metrics.data.RepositoryMetricsAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
The startup log for the successful deployment is
The only difference I can see between the successful deployment and failed deployment is, the container is loading and initializing the PropertySourceBootstrapConfiguration bean by itself for successful deployment
This is linked to the same question asked by me in this post but didnt get any resposne
Upgrading from Springboot 2.1.4.RELEASE to 2.5.0 giving IllegalArgumentException on runtime
Below is the build.gradle:
buildscript {
ext {
springBootVersion = '2.5.0'
}
repositories {
mavenCentral()
jcenter()
maven {
url "https://xxxxxx/ARJLY"
credentials {
username = "${artifactory_user}"
password = "${artifactory_password}"
}
name = "xxxxxxx"
}
maven { url "https://repo.spring.io/plugins-release" }
maven { url "https://repo.spring.io/libs-release" }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
//docker
classpath('se.transmode.gradle:gradle-docker:1.2')
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'maven-publish'
apply plugin: 'distribution'
apply plugin: 'application'
apply plugin: 'docker'
apply plugin: 'jacoco'
group = 'com.ge.digital.oa.moa'
archivesBaseName = 'moa-svc'
sourceCompatibility = 1.8
wrapper {
gradleVersion = '6.8'
}
//dependencyManagement {
// imports {
// mavenBom 'org.springframework.cloud:spring-cloud-aws:2.0.1.RELEASE'
// }
//}
repositories {
mavenCentral()
add buildscript.repositories.getByName("oa-publish-repo")
maven { url "https://repo.spring.io/libs-release" }
}
mainClassName = "com.ge.digital.oa.moa.MoaApplication"
eclipse {
classpath {
downloadSources = true
}
}
configurations {
developmentOnly
runtimeClasspath {
extendsFrom developmentOnly
}
}
sourceSets {
generated
}
sourceSets.generated.java.srcDirs = ['src/main/generated']
configurations{
querydslapt
}
dependencies {
implementation('com.ge.digital.oa.common:oa-common:3.0.0') {
exclude module: 'slf4j-log4j12'
exclude group: 'io.micrometer', module: 'micrometer-core'
exclude group: 'org.springframework.hateoas', module: 'spring-hateoas'
//exclude group: 'org.springframework.cloud', module: 'spring-cloud-context'
}
//implementation('org.springframework.security:spring-security-oauth2-client')
implementation('org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.5.0')
implementation('org.springframework.boot:spring-boot-starter-web')
implementation('org.springframework.boot:spring-boot-starter-webflux')
implementation('org.springframework.boot:spring-boot-starter-data-jpa')
implementation('org.apache.commons:commons-lang3');
implementation('commons-fileupload:commons-fileupload:1.4')
implementation("com.h2database:h2")
implementation('org.postgresql:postgresql:42.2.13')
compileOnly('org.projectlombok:lombok')
annotationProcessor('org.projectlombok:lombok')
implementation('org.springframework.boot:spring-boot-starter-actuator')
implementation("org.flywaydb:flyway-core")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.junit.jupiter:junit-jupiter-engine")
developmentOnly("org.springframework.boot:spring-boot-devtools")
implementation('com.opencsv:opencsv:5.5')
compile ("org.apache.commons:commons-csv:1.5")
compile("com.querydsl:querydsl-core:4.2.1")
compile("com.querydsl:querydsl-jpa:4.2.1")
compile("com.querydsl:querydsl-apt:4.2.1:jpa")
annotationProcessor(
"javax.persistence:javax.persistence-api",
"com.querydsl:querydsl-apt:4.2.1:jpa"
)
implementation("org.hibernate:hibernate-envers:5.4.31.Final")
// https://mvnrepository.com/artifact/com.vladmihalcea/hibernate-types-52
implementation group: 'com.vladmihalcea', name: 'hibernate-types-52', version: '2.10.3'
//OSS Scan fix
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-validation
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-validation', version: '2.5.0'
// https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-context
implementation group: 'org.springframework.cloud', name: 'spring-cloud-context', version: '3.0.0'
// https://mvnrepository.com/artifact/commons-io/commons-io
implementation group: 'commons-io', name: 'commons-io', version: '2.7'
// https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on
implementation group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.64'
// https://mvnrepository.com/artifact/com.google.guava/guava
implementation group: 'com.google.guava', name: 'guava', version: '30.0-jre'
// https://mvnrepository.com/artifact/org.springframework.security.oauth/spring-security-oauth2
//implementation group: 'org.springframework.security.oauth', name: 'spring-security-oauth2', version: '2.3.6.RELEASE'
// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.12.0'
// https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-aws-secrets-manager-config
implementation group: 'org.springframework.cloud', name: 'spring-cloud-starter-aws-secrets-manager-config', version: '2.2.6.RELEASE'
compile group: 'com.amazonaws', name: 'aws-java-sdk-secretsmanager', version: '1.11.355'
// https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-dependencies
//runtimeOnly group: 'org.springframework.cloud', name: 'spring-cloud-dependencies', version: '2020.0.3', ext: 'pom'
Update:
As suggested, I tried this option in application.yml too..but to no success
spring:
config:
activate:
on-profile: aws
use-legacy-processing: true
main:
allow-bean-definition-overriding: true
I got this while deploying the spring boot war on tomcat 9.I have tried many solutions like cleaning project and every possible solution that i found in stackoverflow, But nothing worked, one of them are providing absolute ordering in web.xml, but its a spring boot application so i don't need to use a web.xml file.The application has been woorking perfectly with the localhost and problem comes when i deploy the war file on server.Below is the error.
23-Aug-2019 04:03:25.139 INFO [Catalina-utility-2] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive [/opt/apache-tomcat/webapps/LoopServer.war]
23-Aug-2019 04:03:27.100 SEVERE [Catalina-utility-2] org.apache.catalina.startup.HostConfig.deployWAR Error deploying web application archive [/opt/apache-tomcat/webapps/LoopServer.war]
java.lang.IllegalStateException: Error starting child
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:716)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:690)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:695)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:978)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1849)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)
at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:773)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:427)
at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1620)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:305)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:123)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1144)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1346)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1350)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1328)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/LoopServer]]
at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:198)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:713)
... 25 more
Caused by: java.lang.IllegalArgumentException: More than one fragment with the name [spring_web] was found. This is not legal with relative ordering. See section 8.2.2 2c of the Servlet specification for details. Consider using absolute ordering.
at org.apache.tomcat.util.descriptor.web.WebXml.orderWebFragments(WebXml.java:2257)
at org.apache.tomcat.util.descriptor.web.WebXml.orderWebFragments(WebXml.java:2215)
at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1127)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:768)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:301)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:123)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5048)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
... 26 more
23-Aug-2019 04:03:27.103 INFO [Catalina-utility-2] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [/opt/apache-tomcat/webapps/LoopServer.war] has finished in [1,964] ms
Below is my gradle dependency congiguration
group 'com.lss.loopserver'
version '1.0-SNAPSHOT'
buildscript {
ext {
springBootVersion = '2.1.2.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath("javax.servlet:javax.servlet-api:4.0.1")
}
}
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'war'
war {
baseName = 'LoopServer'
version = '0.0.1'
}
sourceCompatibility = 1.8
repositories {
mavenCentral()
jcenter()
maven { url "http://repo.spring.io/libs-snapshot" }
}
configurations {
providedRuntime
compile.exclude module: 'spring-boot-starter-tomcat'
all*.exclude module: 'spring-boot-starter-logging'
}
dependencies {
testImplementation group: 'junit', name: 'junit', version: '4.12'
implementation('org.springframework.boot:spring-boot-starter-actuator')
implementation('org.springframework.boot:spring-boot-starter-data-jpa') {
exclude group: 'com.zaxxer', module: 'HikariCP'
}
implementation('org.springframework.cloud:spring-cloud-starter-oauth2')
implementation('org.springframework.boot:spring-boot-starter-security') {
exclude group: 'org.springframework', module: 'spring-aop'
}
implementation('org.springframework.boot:spring-boot-starter-aop')
implementation("org.springframework.boot:spring-boot-starter-web") {
exclude module: "spring-boot-starter-tomcat"
}
providedCompile('javax.servlet:javax.servlet-api:4.0.1')
compile('javax.el:javax.el-api:3.0.0')
compile('javax.validation:validation-api:2.0.1.Final')
compile('org.hibernate:hibernate-validator:5.4.1.Final')
providedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
implementation('javax.inject:javax.inject:1')
implementation('mysql:mysql-connector-java:6.0.6')
implementation('joda-time:joda-time:2.10.2')
implementation ('com.google.code.gson:gson:2.8.1')
implementation group: 'commons-fileupload', name: 'commons-fileupload', version: '1.3.3'
implementation ('org.apache.commons:commons-io:1.3.2')
runtime('org.springframework.boot:spring-boot-devtools')
runtime('com.h2database:h2')
testImplementation('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:Greenwich.RC2"
}
}
bootRun {
sourceResources sourceSets.main
}
application.yml :
server:
port: 8080
servlet:
context-path: /LoopServer
spring:
datasource:
url: jdbc:mysql://${db.host:localhost}:${db.port:3306}/${db.name:loopschool}?useSSL=false
username: ${db.uid:root}
password: ${db.pwd:password}
driver-class-name: com.mysql.cj.jdbc.Driver
tomcat:
test-while-idle: true
validation-query: SELECT 1
type: com.mysql.cj.jdbc.MysqlDataSource
jpa:
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL5Dialect
id:
new_generator_mappings: false
format_sql: true
hibernate:
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
ddl-auto: validate
open-in-view: false
application:
name: LoopServer
jmx:
default-domain: LoopServer
main:
allow-bean-definition-overriding: true
devtools:
livereload:
enabled: false
logging:
level:
org:
hibernate:
SQL: DEBUG
type:
descriptor:
sql:
BasicBinder: TRACE
Main class :
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
#SpringBootApplication
public class Main extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Main.class);
}
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
If anyone know any idea about the error please help me.
Clean server (It was tomcat in my case)
OR
Remove tomcat server and artifact Id. Configure again and it will work fine
Finally i found some solution, it looks like there was some spring dependency conflicts was there.So what i was done is simple recreated the project with another name, then it started to work and the error also gone.
Another possible solution is to clean your server in the right way(I haven't tried that, but i think it will work).
Use below command in your intelliJ terminal.
Gradle clean and build command inside project folder :
gradlew clean build
2.To refresh dependencies :
gradlew --refresh-dependencies
Also check your tomcat/webapps/Project/WEB-INF/lib/
folder for dependency conflict during library upgrade.
I did not use Spring Security but it is asking me to authenticate.
Exception for URL(http://localhost:8080/SpringJob/ExecuteJob):
{
"timestamp": 1500622875056,
"status": 401,
"error": "Unauthorized",
"message": "Bad credentials",
"path": "/SPPA/ExecuteSPPAJob"
}
----below log details
2017-07-21 13:15:35.210 INFO 19828 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/SpringJob] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-07-21 13:15:35.210 [http-nio-8080-exec-1] INFO
o.a.c.c.C.[.[localhost].[/SpringJob]-Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-07-21 13:15:35.211 INFO 19828 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2017-07-21 13:15:35.211 [http-nio-8080-exec-1] INFO
o.s.web.servlet.DispatcherServlet-FrameworkServlet 'dispatcherServlet': initialization started
2017-07-21 13:15:35.494 INFO 19828 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 282 ms
2017-07-21 13:15:35.494 [http-nio-8080-exec-1] INFO
o.s.web.servlet.DispatcherServlet-FrameworkServlet 'dispatcherServlet': initialization completed in 282 ms
application-dev.xml
#Spring Boot based configurations
management.security.enabled: "false"
spring.autoconfigure.exclude: "org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration"
spring.batch.job.enabled: false
server.contextPath: /SpringJob
build.gradle snippet
plugins {
id 'jacoco'
id 'org.sonarqube' version '2.5'
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: "no.nils.wsdl2java"
apply plugin: 'jacoco'
apply plugin: "org.sonarqube"
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-batch")
compile("org.springframework.boot:spring-boot-starter-mail")
//compile("org.springframework.boot:spring-boot-devtools")
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.5'
compile group: 'org.apache.cxf', name: 'cxf-spring-boot-starter-jaxws', version: '3.1.10'
compile group: 'org.apache.cxf', name: 'cxf-rt-ws-security', version: '3.1.10'
compile("org.springframework.boot:spring-boot-starter-actuator")
testCompile('org.springframework.boot:spring-boot-starter-test')
}
Controller
#Controller
#EnableAutoConfiguration
#EnableBatchProcessing
public class MyController {
#Autowired
JobLauncher jobLauncher;
#RequestMapping("/ExecuteJob")
#ResponseBody
public String callPrelegalJob(#RequestParam("user") String userName, #RequestParam("password") String password) {
log.info("Job is to be launched from controller...");
}
}
In the current version of Spring Boot (v2.1.0.RELEASE), the easiest way to get rid of the security issues is to add "WebSecurityConfig.java" to your project as follows:
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#EnableWebSecurity
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}
Note of course that this removes protection against cross-site request forgery, so this is really only appropriate for simple read-only endpoints.
Try to add below lines in your application.properties file
security.basic.enable: false
security.ignored=/**
According to spring doc, use security.ignored=
Comma-separated list of paths to exclude from the default secured
paths
Just remove the the spring security dependency from pom.xml file.
Worked for me :)..
if we use CXF security & Spring boot security it gives this issues.
Comment out dependency i.e disable the spring boot security then it allows.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
To enable this we have to write custom security or add below config
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().permitAll();
}
}
Exact way to disable authentication could not be found by me.But by removing actuator dependency which is working.
compile("org.springframework.boot:spring-boot-starter-actuator")
You can configure the springSecurityFilterChain to ignore all requests and thus allow unauthenticated access to all your endpoints with the following:
#Configuration
#EnableWebSecurity
public class WebConfiguration extends WebSecurityConfigurerAdapter {
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/**");
}
}
#harshit-sharma 's solution worked for me; I added exclusion in my main Application class:
#SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
Spring Security may still be in the project libs via transitive dependencies. What should still work in Spring Boot is the following:
#Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**")
.permitAll();
}
Note: the http is a org.springframework.security.config.annotation.web.builders.HttpSecurity and this is in a #Component that may already be injected into and called by some org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter implementation in your application's framework. This should override any built-in catch-all clause, i.e. http.authorizeRequests().anyRequest().denyAll() for testing purposes etc..
I solved by removed this dependency from pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
I'm using Gradle to manage my dependencies for Hibernate (I was previously using Maven), but I've encountered something strange. When I try to save a trivial instance of an annotated class to the database I wind up getting a MappingException saying said class is not mapped. This situation is somewhat unique because of the way I've been storing the instances. Assume that the situation is this: I have a properly annotated hibernate class that will be saved using the Session from an EntityManager using saveOrUpdate(). I have a persistance.xml, but no hibernate configuration files. I'm relying on the EntityManagers auto detection of mapped classes to feed it to the Session so it can be recognized as properly annotated. I'm using Hibernate 4.3.8. The code worked before the switch. All method calls take place in a transactional context and the transaction is committed and the session flushed.
Exception:
Caused by: org.hibernate.MappingException: Unknown entity: com.gmail.sarah.project.Rank
Gradle Dependencies:
compile "org.hibernate:hibernate-core:4.3.8.Final"
compile "org.hibernate:hibernate-entitymanager:4.3.8.Final"
compile "org.hibernate:hibernate-ehcache:4.3.8.Final"
compile "mysql:mysql-connector-java:5.1.35"
EDIT (A test case also has the same problem):
Main Class:
package com.gmail.physicistsarah.gradletestproject.core;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Table;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class Init {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("Test_Project");
EntityManager manager = factory.createEntityManager();
Session session = manager.unwrap(Session.class);
Transaction transaction = session.getTransaction();
transaction.begin();
session.saveOrUpdate(new Person("Carl", "Gauss"));
session.saveOrUpdate(new Person("Benoit", "Mandelbrot"));
transaction.commit();
factory.close();
}
#Entity
#Table(name = "Person")
public static class Person {
#Column(name = "First_Name", nullable = false)
private final String firstName;
#Column(name = "Last_Name", nullable = false)
private final String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
}
Persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="Test_Project" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test_project_db?zeroDateTimeBehavior=convertToNull"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
Build.gradle:
apply plugin: 'java'
apply plugin:'application'
sourceCompatibility = '1.8'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
// NetBeans will automatically add "run" and "debug" tasks relying on the
// "mainClass" property. You may however define the property prior executing
// tasks by passing a "-PmainClass=<QUALIFIED_CLASS_NAME>" argument.
//
// Note however, that you may define your own "run" and "debug" task if you
// prefer. In this case NetBeans will not add these tasks but you may rely on
// your own implementation.
mainClassName = "com.gmail.physicistsarah.gradletestproject.core.Init"
if (!hasProperty('mainClass')) {
ext.mainClass = 'com.gmail.physicistsarah.gradletestproject.core.Init'
}
task sourcesJar(type: Jar, dependsOn: classes) {
classifier = 'sources'
from sourceSets.main.allSource
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
artifacts {
archives sourcesJar
archives javadocJar
}
repositories {
mavenCentral()
// You may define additional repositories, or even remove "mavenCentral()".
// Read more about repositories here:
// http://www.gradle.org/docs/current/userguide/dependency_management.html#sec:repositories
}
dependencies {
// TODO: Add dependencies here ...
// You can read more about how to add dependency here:
// http://www.gradle.org/docs/current/userguide/dependency_management.html#sec:how_to_declare_your_dependencies
compile "org.hibernate:hibernate-core:4.3.8.Final"
compile "org.hibernate:hibernate-entitymanager:4.3.8.Final"
compile "org.hibernate:hibernate-ehcache:4.3.8.Final"
compile "mysql:mysql-connector-java:5.1.35"
testCompile group: 'junit', name: 'junit', version: '4.10'
}
Exception:
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.gmail.physicistsarah.gradletestproject.core.Init$Person
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1096)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1443)
at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:242)
at org.hibernate.event.internal.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:511)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:100)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:684)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:676)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:671)
at com.gmail.physicistsarah.gradletestproject.core.Init.main(Init.java:23)
The persistence.xml (and META-INF package) are in the resources/main folder.
You have many errors in your code:
Entities may not be nested classes
Entities must have a no-arg constructor
Entities fields may not be final
Entities must have an attribute annotated with #Id
Entities must be listed in the persistence.xml file:
<class>com.foo.bar.EntityClassName</class>
Inside a controller my code was not persisting when I called .persist. I've also included my AppConfig for reference as well as my gradle dependencies. This is all on Tomcat7.
Persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="main">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/dirtylibs"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="password"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
Gradle
testCompile group: 'junit', name: 'junit', version: '4.11'
providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.0.1'
compile group: 'org.springframework', name: 'spring-webmvc', version: '3.2.5.RELEASE'
compile group: 'org.springframework', name: 'spring-orm', version: '3.2.5.RELEASE'
compile group: 'org.hibernate', name: 'hibernate-core', version: '4.3.0.Final'
compile group: 'org.hibernate', name: 'hibernate-entitymanager', version: '4.3.0.Final'
runtime group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.3.0'
runtime group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.3.0'
runtime group: 'mysql', name:'mysql-connector-java', version: '5.1.26'
AppConfig
#Configuration
#EnableWebMvc
#ComponentScan(basePackageClasses = AppConfig.class)
#EnableTransactionManagement
public class AppConfig {
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
return resolver;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
Class.forName("com.mysql.jdbc.Driver").newInstance(); //This is some wierdness I needed to do because the mysql driver wasn't being picked up correctly
LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
return localContainerEntityManagerFactoryBean;
}
}
My Controller
#Controller
public class SampleController {
#PersistenceContext
EntityManager entityManager;
#RequestMapping("home/test/{id}")
#ResponseBody
public List<Integer> getMessagesTest(#PathVariable Integer id) {
Phrase phrase = new Phrase();
entityManager.persist(phrase);
return Arrays.asList(phrase.getId());
}
}
According to
EntityManager persist() method does not insert record to database => SEVERE: javax.persistence.TransactionRequiredException
To persist data to a database using an entity manager I need to have it wrapped up in a transaction, which will call .flush() for me at the end of the transaction. Which means I need to add #Transaction to my controller, which I did. Now it looks like this.
#RequestMapping("home/test/{id}")
#ResponseBody
#Transactional
public List<Integer> getMessagesTest(#PathVariable Integer id) {
Phrase phrase = new Phrase();
entityManager.persist(phrase);
return Arrays.asList(phrase.getId());
}
http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/orm/hibernate4/HibernateTransactionManager.html
Once I do that, I get the following exception.
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.transaction.PlatformTransactionManager] is defined
Okay, no problem. It looks like the Hibernate 4 HibernateTransactionManager will do the job. Once I started to configure the HibernateTransactionManager in my AppConfig I realized I also needed a SessionFactory.
I very confused by all the options for creating a SessionFactory, and how it relates to my persistence.xml
My main question is how should I construct my session factory given my current setup?
Looking at the Spring docs it looks like I have to repeat all the information from my persistence.xml which seems really wrong to me. http://docs.spring.io/spring/docs/3.0.x/reference/orm.html#orm-hibernate
Any help would be much appreciated, including critique of the current setup. I really want to stick with the Java config, and avoid as much XML as possible. I'd even like to move away from the persistence-config.xml as described here, but I wanted to wait until it was working before trying that.
http://spring.io/blog/2011/06/10/spring-3-1-m2-configuration-enhancements/
Bozho's post over at Best Way to Inject Hibernate Session by Spring 3 gave me the information I needed to get it all tied together. I still haven't figured out if I need the persistence.xml, but now I'm recording entities to the database.
My new AppConfig now looks like this
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
Class.forName("com.mysql.jdbc.Driver").newInstance();
LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect");
hibernateJpaVendorAdapter.setShowSql(true);
localContainerEntityManagerFactoryBean.setJpaVendorAdapter(hibernateJpaVendorAdapter);
return localContainerEntityManagerFactoryBean;
}
#Bean
BasicDataSource basicDataSource() {
BasicDataSource basicDataSource = new BasicDataSource();
basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
basicDataSource.setUrl("jdbc:mysql://localhost:3306/dirtylibs");
basicDataSource.setUsername("root");
basicDataSource.setPassword("password");
return basicDataSource;
}
#Bean
JpaTransactionManager jpaTransactionManager(LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean) {
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(localContainerEntityManagerFactoryBean.getObject());
return jpaTransactionManager;
}
I had to pull in another dependency for the BasicDataSource which came from Apache. Here are the Gradle coordinates.
compile group: 'commons-dbcp', name: 'commons-dbcp', version: '1.4'