I'm trying to solve my inheritance problem with kotlin sealed class and forced problem with hibernate.
Here are my classes:
#Entity
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
sealed class LegalGuardian(
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Int? = null
)
#Entity
#DiscriminatorValue(value = "MOTHER")
data class MotherLegalGuardian(
#OneToOne(cascade = [CascadeType.ALL], orphanRemoval = true)
val pesel: Pesel
) : LegalGuardian()
#Entity
#DiscriminatorValue(value = "OTHER")
data class OtherLegalGuardian(
val firstName: String,
val lastName: String,
#OneToOne
val address: Address
) : LegalGuardian()
Here is poroblem that is thrown:
Caused by: org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:123)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77)
at org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:348)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879)
... 95 common frames omitted
Caused by: org.hibernate.InstantiationException: could not instantiate test object : X.MotherLegalGuardian
at org.hibernate.engine.internal.UnsavedValueFactory.instantiate(UnsavedValueFactory.java:43)
at org.hibernate.engine.internal.UnsavedValueFactory.getUnsavedIdentifierValue(UnsavedValueFactory.java:68)
at org.hibernate.tuple.PropertyFactory.buildIdentifierAttribute(PropertyFactory.java:61)
at org.hibernate.tuple.entity.EntityMetamodel.(EntityMetamodel.java:141)
at org.hibernate.persister.entity.AbstractEntityPersister.(AbstractEntityPersister.java:517)
at org.hibernate.persister.entity.SingleTableEntityPersister.(SingleTableEntityPersister.java:124)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
... 99 common frames omitted
Caused by: java.lang.reflect.InvocationTargetException: null
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.hibernate.engine.internal.UnsavedValueFactory.instantiate(UnsavedValueFactory.java:40)
... 109 common frames omitted
Caused by: java.lang.NoSuchMethodError: X.LegalGuardian.(Lkotlin/jvm/internal/DefaultConstructorMarker;)V
at X.MotherLegalGuardian.(LegalGuardian.kt)
... 114 common frames omitted
I don't know how hibernate works.
But I guess the issue is related to this notes from sealed-classes docs:
A sealed class is abstract by itself, it cannot be instantiated
directly and can have abstract members.
Sealed classes are not allowed to have non-private constructors (their
constructors are private by default).
It looks like the problem is not in sealed class, but in the data class and constructors. When you are using primary constructors with arguments, there is no default (no-arguments) constructor, which is required for hibernate. You can see the reason in the very end of the stacktrace:
java.lang.NoSuchMethodError: X.LegalGuardian.(Lkotlin/jvm/internal/DefaultConstructorMarker;)V at X.MotherLegalGuardian.(LegalGuardian.kt)
You can enable no-arg and jpa-support plugins to get no-arg constructors generated.
Check out also this article which explains why data classes are not a good choice for hibernate.
Related
I have a Spring Batch that has a writer to an Azure Storage Blob.
I am using this Azure/Spring Dependency:
azure-spring-boot-starter-storage 3.4.0
On my application properties I have:
azure.storage.accountName=myAccount
azure.storage.accountKey=myKey
Then inside my BatchConfig class I autowired the AZ Storage:
#Autowired
private BlobServiceClientBuilder blobServiceClientBuilder;
private final BlobServiceAsyncClient blobServiceAsyncClient = blobServiceClientBuilder.buildAsyncClient();
Now when I start my application, I am getting a NullPointerException because the BlobServiceClientBuilder cannot be instantiated.
Caused by: java.lang.NullPointerException: null
at com.example.dbreader.configuration.BatchConfig.<init>(BatchConfig.java:55) ~[classes/:na]
at com.example.dbreader.configuration.BatchConfig$$EnhancerBySpringCGLIB$$58787751.<init>(<generated>) ~[classes/:na]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_221]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_221]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_221]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_221]
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:212) ~[spring-beans-5.3.5.jar:5.3.5]
What am I doing wrong when autowiring the Azure Blob Bean?
One more thing I am using the Spring Resource to instantiate a blob file:
#Value("blob://{containerName}/" + "#{stepExecutionContext['marketName']}")
private Resource blobFile;
Encountered the same issue . Looks like its a mistake from documentation.
Azure.storage.blob-endpoint property is mandatory for blobClient and optional for fileClient. Add
Azure.storage.blob-endpoint= https://<account-name>.blob.core.windows.net
to resolve the issue
I encountered the same issue. finally I found that the buildClient() method couldn't be put in global or constructor. just put it in the GET/POST method, it'll work. FYR.
#Autowired
private BlobServiceClientBuilder blobServiceClientBuilder;
private BlobServiceClient blobServiceClient;
#GetMapping
public String readBlobFile() throws IOException {
blobServiceClient = blobServiceClientBuilder.buildClient();
AzureStorageResourcePatternResolver storageResourcePatternResolver = new AzureStorageResourcePatternResolver(blobServiceClient);
when run the application, it throws IllegalAccessError,Application run failed
here is demo aop、service、annotation used,a simple annotation and #Before advice,also enable #EnableAspectJAutoProxy
#Target({ElementType.TYPE, ElementType.METHOD})
#Retention(RetentionPolicy.RUNTIME)
public #interface MethodInterceptAnnotation {
}
#Component
#Aspect
public class MethodInterceptAop {
#Before("#target(com.example.demo.aop.MethodInterceptAnnotation)")
public void beforeCheck() {
System.out.println("before check");
}
}
public interface UserService {
String getUserName(int a);
}
#Service
public class UserServiceImpl implements UserService {
#MethodInterceptAnnotation
public String getUserName(int age) {
System.out.println("age:" + age);
return age + "";
}
}
change#target to #within error again,
but change#target to #annotation everything is ok
here is partial stacktrace
Caused by: org.springframework.cglib.core.CodeGenerationException: java.lang.IllegalAccessError-->class org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryConfiguration$EmbeddedTomcat$$EnhancerBySpringCGLIB$$e5c9e457 cannot access its superclass org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryConfiguration$EmbeddedTomcat
at org.springframework.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:538) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:363) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.cglib.proxy.Enhancer.generate(Enhancer.java:582) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:110) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:108) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.cglib.core.internal.LoadingCache$2.call(LoadingCache.java:54) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_201]
at org.springframework.cglib.core.internal.LoadingCache.createEntry(LoadingCache.java:61) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.cglib.core.internal.LoadingCache.get(LoadingCache.java:34) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:134) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:319) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:569) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:416) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.aop.framework.ObjenesisCglibAopProxy.createProxyClassAndInstance(ObjenesisCglibAopProxy.java:57) ~[spring-aop-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:205) ~[spring-aop-5.2.4.RELEASE.jar:5.2.4.RELEASE]
... 37 common frames omitted
Caused by: java.lang.IllegalAccessError: class org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryConfiguration$EmbeddedTomcat$$EnhancerBySpringCGLIB$$e5c9e457 cannot access its superclass org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryConfiguration$EmbeddedTomcat
at java.lang.ClassLoader.defineClass1(Native Method) ~[na:1.8.0_201]
at java.lang.ClassLoader.defineClass(ClassLoader.java:763) ~[na:1.8.0_201]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_201]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_201]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_201]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_201]
at org.springframework.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:535) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
... 51 common frames omitted
anyone know what is wrong with this code, thanks in advance.
From the documentation : Supported Pointcut Designators
#target: Limits matching to join points (the execution of methods when
using Spring AOP) where the class of the executing object has an
annotation of the given type.
#within: Limits matching to join points within types that have the
given annotation (the execution of methods declared in types with the
given annotation when using Spring AOP).
Both #target and #within advice types are for the class/type .
The scope of the pointcut is global and when the application starts up it tries to identify all the classes/types with annotation and interferes with unwanted classes , here EmbeddedTomcat related.
For #target and #within advice types to work , try narrowing the scope by adding a scoping designator as follows
#Before("#target(com.example.demo.aop.MethodInterceptAnnotation) && within(com.example.demo..*)")
For me , narrowing the scope have always worked , but have come across SO questions where that too did not help. In that case , resolution for your issue is available in this answer from #kriegaex.
Please go through the answer and comments to understand the difference when #annotation is used. To summarize , advice types #target and #within when used , tends to create proxies for all classes irrespective if the annotation is present or not at class level.
Hope this helps.
Hi I am having a springboot application. while trying to run a junit spring integration test i am getting an error.
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.openmind.primecast.config.LoggingConfiguration$$EnhancerBySpringCGLIB$$4afbeba5]: Constructor threw exception; nested exception is java.lang.LinkageError: loader constraint violation: loader (instance of org/powermock/core/classloader/MockClassLoader) previously initiated loading for a different type with name "javax/net/SocketFactory"
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:122)
at org.springframework.beans.factory.support.ConstructorResolver$1.run(ConstructorResolver.java:265)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:262)
... 50 common frames omitted
Caused by: java.lang.LinkageError: loader constraint violation: loader (instance of org/powermock/core/classloader/MockClassLoader) previously initiated loading for a different type with name "javax/net/SocketFactory"
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at org.powermock.core.classloader.MockClassLoader.loadUnmockedClass(MockClassLoader.java:262)
at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:206)
at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:89)
at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:79)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at com.openmind.primecast.config.LoggingConfiguration.addLogstashAppender(LoggingConfiguration.java:66)
at com.openmind.primecast.config.LoggingConfiguration.<init>(LoggingConfiguration.java:49)
at com.openmind.primecast.config.LoggingConfiguration$$EnhancerBySpringCGLIB$$4afbeba5.<init>(<generated>)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)
... 54 common frames omitted
this is my junit test class
#RunWith(PowerMockRunner.class)
#PowerMockIgnore({"javax.management.*", "javax.net.ssl.*"})
#SpringBootTest(classes = PrimecastApp.class)
#PowerMockRunnerDelegate(SpringRunner.class)
#PrepareForTest(com.openmind.primecast.security.SecurityUtils.class)
#WithMockUser
public class CampaignResourceIntTest extends AbstractCassandraTest {
#Test
#WithMockUser
public void getCsvForPerformanceNotFound() throws Exception {
PowerMockito.mockStatic(com.openmind.primecast.security.SecurityUtils.class);
BDDMockito.given(com.openmind.primecast.security.SecurityUtils.getCurrentUserLogin()).willReturn(Optional.of(user.getLogin()));
UserDTO userDto = new UserDTO();
userDto.setAccount(null);
when(userService.getUserWithAuthoritiesByLogin(anyString())).thenReturn(userDto);
restCampaignMockMvc.perform(get("/api/campaigns/{id}/performance/csv", UUID.randomUUID()))
.andExpect(status().isNotFound());
}
}
i have no clue . I am using this in my test #PowerMockIgnore({"javax.management.", "javax.net.ssl."})
really appreciate any help
thank you
I'm using Hibernate and Spring to create a Rest Api.
I'm mapping a Trainer to a table in mySQL
Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List io.fruitful.model.repos.TrainerRepository.getTrainerByFilter(java.lang.String,java.lang.Integer)!
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:93) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.<init>(SimpleJpaQuery.java:63) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromMethodWithQueryString(JpaQueryFactory.java:76) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromQueryAnnotation(JpaQueryFactory.java:56) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$DeclaredQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:139) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:206) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:79) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lookupQuery(RepositoryFactorySupport.java:553) ~[spring-data-commons-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$mapMethodsToQuery$1(RepositoryFactorySupport.java:546) ~[spring-data-commons-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) ~[na:1.8.0_144]
at java.util.Iterator.forEachRemaining(Iterator.java:116) ~[na:1.8.0_144]
at java.util.Collections$UnmodifiableCollection$1.forEachRemaining(Collections.java:1049) ~[na:1.8.0_144]
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) ~[na:1.8.0_144]
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) ~[na:1.8.0_144]
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) ~[na:1.8.0_144]
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) ~[na:1.8.0_144]
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:1.8.0_144]
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499) ~[na:1.8.0_144]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.mapMethodsToQuery(RepositoryFactorySupport.java:548) ~[spring-data-commons-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$new$0(RepositoryFactorySupport.java:538) ~[spring-data-commons-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at java.util.Optional.map(Optional.java:215) ~[na:1.8.0_144]
and
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: trainers is not mapped [SELECT t from trainers t WHERE t.trainerName = :name AND t.accountId = :id]
at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:79) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:217) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:141) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:77) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:553) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:662) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
... 79 common frames omitted
Entity:
#Entity
#Table(name = "trainers")
public class Trainer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "trainer_id", unique = true, nullable = false)
private Integer trainerId;
#Column (name = "trainer_name")
private String trainerName;
#Column (name = "account_id")
private Integer accountId;
Here is the Repo code:
#Query(value = "SELECT t from trainers t WHERE t.trainerName = :name AND t.accountId = :id")
List<Trainer> getTrainerByFilter(#Param("name") String name,
#Param("id") Integer id);
#Query(value = "SELECT * from trainers where account_id is null", nativeQuery = true)
List getTrainerNoAccount();
ConfigSql:
environment.setPackagesToScan("io.fruitful.model");
The getTrainerNoAccount() is working fine.
Hibernate maps your entity as Trainer, the name of your class, since you didn't specified the name param in #Entity annotation.
Thus, your query should be "SELECT t from Trainer t...".
getTrainerNoAccount() works fine because its #Query is set as native, using the table name and not your entity name.
#Query(value = "SELECT t from Trainer t WHERE t.trainerName = :name AND t.accountId = :id")
List<Trainer> getTrainerByFilter(#Param("name") String name,
#Param("id") Integer id);
Change your Query like that because JPA needs bean name rather table name.
I am initializing my cache in the following way:
CacheManager cacheManager;
cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build();
cacheManager.init();
Cache<String, SmsMessageDto> myCache = cacheManager.createCache("myCache", CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, SmsMessageDto.class)
.withExpiry(Expirations.timeToLiveExpiration(new Duration(cacheDuration, TimeUnit.MINUTES)))
.build());
Which gives me the following warning:
org.ehcache.core.EhcacheManager - Could not create serializers for myCache
org.ehcache.spi.serialization.UnsupportedTypeException: No serializer found for type 'com.example.dto.SmsMessageDto'
at org.ehcache.impl.internal.spi.serialization.DefaultSerializationProvider$AbstractProvider.getClassFor(DefaultSerializationProvider.java:271) ~[ehcache-3.0.0.rc1.jar:3.0.0.rc1]
at org.ehcache.impl.internal.spi.serialization.DefaultSerializationProvider$TransientProvider.createSerializer(DefaultSerializationProvider.java:149) ~[ehcache-3.0.0.rc1.jar:3.0.0.rc1]
at org.ehcache.impl.internal.spi.serialization.DefaultSerializationProvider$AbstractProvider.createValueSerializer(DefaultSerializationProvider.java:239) ~[ehcache-3.0.0.rc1.jar:3.0.0.rc1]
at org.ehcache.impl.internal.spi.serialization.DefaultSerializationProvider.createValueSerializer(DefaultSerializationProvider.java:96) ~[ehcache-3.0.0.rc1.jar:3.0.0.rc1]
at org.ehcache.core.EhcacheManager.getStore(EhcacheManager.java:455) [ehcache-3.0.0.rc1.jar:3.0.0.rc1]
at org.ehcache.core.EhcacheManager.createNewEhcache(EhcacheManager.java:308) [ehcache-3.0.0.rc1.jar:3.0.0.rc1]
at org.ehcache.core.EhcacheManager.createCache(EhcacheManager.java:261) [ehcache-3.0.0.rc1.jar:3.0.0.rc1]
at org.ehcache.core.EhcacheManager.createCache(EhcacheManager.java:240) [ehcache-3.0.0.rc1.jar:3.0.0.rc1]
at at.xcard.helper.SmsFailedCache.init(SmsFailedCache.java:45) [classes/:na]
at at.xcard.SmsWorker.<init>(SmsWorker.java:49) [classes/:na]
at at.xcard.Main.main(Main.java:36) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_25]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_25]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_25]
at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_25]
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) [idea_rt.jar:na]
How can I convince EhCache to use my toString method of the com.example.dto.SmsMessageDto object?
In short it is not possible. You have to implement Serializable interface in your class SmsMessageDto. It will create a serializer for your Serializable class and the Exception will not display again. This answer was based in the following link http://www.ehcache.org/documentation/3.1/serializers-copiers.html section Bundled implementations.
From the documentation:
By default, cache managers are pre-configured with specially optimized
Serializer that can handle the following types, in the following
order:
java.io.Serializable
java.lang.Long
java.lang.Integer
java.lang.Float
java.lang.Double
java.lang.Character
java.lang.String
byte[]
Given that you are not using the offheap or disk tier, there is no requirement for a serializer.
Now I see you are using version 3.0.0.rc1. I would strongly recommend not using an RC at this point and instead use the latest (at this time) 3.1.2.
I believe what you are experiencing is a bug that has most likely been fixed since then.