Spring Data Error with specific object - spring-data

I have the following repository:
public interface ICredCardRepository extends JpaRepository<CredCardEntity, Long> {
public List<CredCardEntity> findByUserId(Long userId);
}
The UserId attribute is declared like this in the CredCardEntity:
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "UserId", nullable = false)
private UserEntity UserId;
I have the following exception:
Caused by: java.lang.RuntimeException:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'ICredCardRepository': Invocation of init
method failed; nested exception is java.lang.IllegalArgumentException:
Could not create query metamodel for method public abstract
java.util.List
org.wpattern.frameworks.jsf.primefaces.model.repositories.ICredCardRepository.findByUserId(java.lang.Long)!
at
io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:223)
at
org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:87)
at
org.wildfly.extension.undertow.deployment.UndertowDeploymentService.start(UndertowDeploymentService.java:72)
at
org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948)
[jboss-msc-1.2.2.Final.jar:1.2.2.Final] at
org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881)
[jboss-msc-1.2.2.Final.jar:1.2.2.Final]
Based on this exception I have changed the method findByUserId like that:
public List<CredCardEntity> findByUserId(UserEntity userId);
But it does not work. Could you help me out, please?

Simply change UserId property name to user. In this case 'UserId' in your method will be pointed to the id property of the User.
Also I think #JoinColumn is unnecessary here, you can remove it...

Related

Hibernate COUNT function can't find column

Currently trying to run a COUNT function in Hibernate that simply returns a count of all platforms in the table.
Query<?> intQuery = session.createQuery("select count(platform) from
UserPlatform");`
Hibernate output in console:
Hibernate: select count(userplatfo0_.PLATFORM) as col_0_0_ from OTS_SCHEMA.OTS_USER_PLATFORM_TBL userplatfo0_
However, I am continually met with the following error when I run the code:
Exception in thread "Thread-9" javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not execute query
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1535)
at org.hibernate.query.internal.AbstractProducedQuery.getSingleResult(AbstractProducedQuery.java:1574)
at com.ots.Utilities.getPrimaryUserPlatformFromWrapper(Utilities.java:677)
at com.ots.Processor$3.run(Processor.java:194)
Caused by: org.hibernate.exception.GenericJDBCException: could not execute query
Caused by: java.sql.SQLException: Column not found: col_0_0_
The Hibernate model class:
#Repository
#Entity
#Table(name="OTS_USER_PLATFORM_TBL")
#Scope("prototype")
public class UserPlatform {
#Id
#Column(name="ID")
private int id;
#Column(name="CWSID")
private String cwsid;
#Column(name="PLATFORM")
private String platform;
#Autowired
public UserPlatform(String cwsid, String platform) {
this.cwsid = cwsid;
this.platform = platform;
}
public UserPlatform() {
}
//getters&setters
}
I suspect Hibernate is looking for a mapping to col_0_0, but as col_0_0 is not a 'real' column, there is no mapping for it. How do we handle this problem in Hibernate?
Your Hibernate model class is way off:
Delete: #Repository
Delete: #Scope
Delete: #Autowired Constructor
You need to show your real service code, i.e. where you execute the query.

NPE on ManyToMany in DataNucleus

I have this entity
#Entity
public class ContactList extends Base {
private static final long serialVersionUID = BaseEntity.serialVersionUID;
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Collection<User> contacts = new HashSet<User>();
public ContactList() {
}
public Collection<User> getContacts() {
return contacts;
}
public void setContacts(Collection<User> contacts) {
this.contacts = contacts;
}
}
and whatever method I call from the Spring Data repository, like findAll(), I get this error
java.lang.NullPointerException: null
at org.datanucleus.store.rdbms.RDBMSStoreManager.assertCompatibleFieldType(RDBMSStoreManager.java:1005) ~[datanucleus-rdbms-4.1.1.jar:na]
at org.datanucleus.store.rdbms.RDBMSStoreManager.getBackingStoreForField(RDBMSStoreManager.java:965) ~[datanucleus-rdbms-4.1.1.jar:na]
at org.datanucleus.store.rdbms.query.BulkFetchExistsHelper.getSQLStatementForContainerField(BulkFetchExistsHelper.java:93) ~[datanucleus-rdbms-4.1.1.jar:na]
at org.datanucleus.store.rdbms.query.JPQLQuery.compileQueryFull(JPQLQuery.java:894) ~[datanucleus-rdbms-4.1.1.jar:na]
at org.datanucleus.store.rdbms.query.JPQLQuery.compileInternal(JPQLQuery.java:296) ~[datanucleus-rdbms-4.1.1.jar:na]
at org.datanucleus.store.query.Query.executeQuery(Query.java:1801) ~[datanucleus-core-4.1.1.jar:na]
at org.datanucleus.store.query.Query.executeWithMap(Query.java:1747) ~[datanucleus-core-4.1.1.jar:na]
at org.datanucleus.api.jpa.JPAQuery.getResultList(JPAQuery.java:197) ~[datanucleus-api-jpa-4.1.1.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:77) ~[spring-data-jpa-1.3.0.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:55) ~[spring-data-jpa-1.3.0.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:95) ~[spring-data-jpa-1.3.0.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:85) ~[spring-data-jpa-1.3.0.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:312) ~[spring-data-commons-1.5.0.RELEASE.jar:na]
Any idea why?
I also tried adding targetEntity = User.class to #ManyToMany.
I'm using DataNucleus 1.4.1.
I found in the log the following lines that could be relevant:
DataNucleus.Datastore.Schema - DEBUG: Field [ContactList.contacts] -> Column(s) [contactlist.contacts] using mapping of type "org.datanucleus.store.rdbms.mapping.java.TypeConverterMapping" (org.datanucleus.store.rdbms.mapping.datastore.VarCharRDBMSMapping)
...
DataNucleus.Persistence - WARN : Member ContactList.contacts in table=contactlist has mapping=org.datanucleus.store.rdbms.mapping.java.TypeConverterMapping#6296ccf7 but expected mapping type=class org.datanucleus.store.rdbms.mapping.java.CollectionMapping
The problem was that a Converter was automatically applied. But I think this is an issue with DataNucleus, because that converter was declared something like this
public class ListOfMyEnumsToStringAttributeConverter
extends CollectionOfEnumsToStringAttributeConverter<MyEnum, List<MyEnum>>
implements AttributeConverter<List<MyEnum>, String>
Another issue with DataNucleus is that NPE is thrown even though a warning/error message should be logged.
And last, but not least, when a converter is automatically applied and this leads to an error, the converter class should be part of the log message.

CORBA exception in EJB application

I've got a problem with EJB/Glassfish. I'm working on a client-server application in which the client creates an entity object and must send it to the server application, which must persist the entity in its database. I've choose to use session beans to communicate with the server.
I've implemented some simple cases in which a method in the session bean takes as input a string or an int and it works fine. The problem arises when I try to give an entity object as input.
I report my entity class:
#Entity
public class Example implements Serializable {
private static final long serialVersionUID = 1L;
#Id
String nome;
public void setNome(String nome) {
this.nome = nome;
}
public String getNome() {
return nome;
}
Here my session bean:
#Stateless
public class GestoreLibreriaRemoto implements GestoreLibreriaRemotoRemote {
#Override
public String getProva(Example prova) {
return prova.getNome();
}
Here my client application:
public class GestoreLibreriaLocale {
public static void assegnaCategoriaACopia(CopiaUtente copia, Categoria categoria) throws
public void prova() {
GestoreLibreriaRemotoRemote gestore = lookupGestoreLibreriaRemotoRemote();
Example example = new Example();
prova.setNome("hodor");
System.out.println(gestore.getProva(example));
}
private GestoreLibreriaRemotoRemote lookupGestoreLibreriaRemotoRemote() {
try {
Context c = new InitialContext();
return (GestoreLibreriaRemotoRemote) c.lookup("java:global/ServerMDB/ServerMDB-ejb/GestoreLibreriaRemoto");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}
In my main class I simply call GestoreLibreriaLocale.prova() and i get the following error:
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.glassfish.appclient.client.acc.AppClientContainer.launch(AppClientContainer.java:446)
at org.glassfish.appclient.client.AppClientFacade.main(AppClientFacade.java:166)
Caused by: javax.ejb.EJBException: java.rmi.MarshalException: CORBA MARSHAL 1330446346 Maybe; nested exception is:
org.omg.CORBA.MARSHAL: ----------BEGIN server-side stack trace----------
org.omg.CORBA.MARSHAL: AVVERTENZA: 00810010: Error from readValue on ValueHandler in CDRInputStream vmcid: OMG minor code: 10 completed: Maybe
at com.sun.proxy.$Proxy139.valuehandlerReadError(Unknown Source)
at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.readRMIIIOPValueType(CDRInputStream_1_0.java:912)
at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.read_value(CDRInputStream_1_0.java:1005)
at com.sun.corba.ee.impl.encoding.CDRInputObject.read_value(CDRInputObject.java:518)
at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl$14.read(DynamicMethodMarshallerImpl.java:383)
at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl.readArguments(DynamicMethodMarshallerImpl.java:450)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:171)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)
Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.sun.corba.ee.impl.io.IIOPInputStream
at com.sun.corba.ee.impl.io.ValueHandlerImpl.createInputStream(ValueHandlerImpl.java:820)
at com.sun.corba.ee.impl.io.ValueHandlerImpl.readValue(ValueHandlerImpl.java:263)
at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.readRMIIIOPValueType(CDRInputStream_1_0.java:903)
... 16 more
The error log continues, I don't report the whole log but if you need it I can post it.
Please help me, I'm working on it from days without resolving it.
Thanks for the attention,
Francesco
This seems to be a bug in the current Java versions (e.g. 1.7.0_55 and 1.8.0_05), have a look at this issue: GLASSFISH-21047
To make it work, install either an older or a newer Java version (e.g. 1.7.0_051 or 1.8.0_020).
See also:
Exception inside CORBA when accessing a remote bean

How do I use inheritance in programming model with JPA?

I'm trying to implement this model using JPA 2.1. I'm using the JSR 338 specification and the reference implementation Eclipselink.
Only entities of the third level and associative classes will be persisted.
#MappedSuperclass
public abstract class PessoaMaster implements Serializable {
private static final long serialVersionUID = 1L;
private long id;
private List<Telefone> telefones;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ID_Pai", unique=true, nullable=false)
public long getId() {
return id;
}
public void setId(long identificador) {
id = identificador;
}
/**
* #return the telefones
*/
#OneToMany
public List<Telefone> getTelefones() {
return telefones;
}
/**
* #param telefones the telefones to set
*/
public void setTelefones(List<Telefone> telefones) {
this.telefones = telefones;
}
}
I can use instead of Inheritance MappedSuperclass here?
#Entity
#Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public abstract class FornecedorSuper extends PessoaMaster{
//attributes and relationships
}
Entity that is persisted.
public class FornecedorPecas extends FornecedorSuper {
private Double Valor;
#Column(name="ValorPeca")
public Double getValor() {
return Valor;
}
public void setValor(Double valor) {
Valor = valor;
}
}
It is necessary to mark FornecedorPeças class with # Entity?
When I insert the MappedSuperclass in the FornecedorSuper. This exception is thrown:
Exception in thread "main" Local Exception Stack: Exception [EclipseLink-30005] (Eclipse Persistence Services - .5.0.v20130507-3faac2b):org.eclipse.persistence.exceptions.PersistenceUnitLoadingException Exception Description: An exception was thrown while searching for persistence archives ith ClassLoader: sun.misc.Launcher$AppClassLoader#affc70 Internal Exception: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [modelo] failed.
Internal Exception: Exception [EclipseLink-7161] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Entity class [class br.miltex.dominio.model.FornecedorPecas] has no primary key specified. It should define either an #Id, #EmbeddedId or an #IdClass. If you have defined PK using any of these annotations then make sure that you do not have mixed access-type (both fields and properties annotated) in your entity class hierarchy.
Q1. I can use instead of Inheritance MappedSuperclass here?
Although I didn't find any examples in the specification with that, the JPA specification says:
The MappedSuperclass annotation designates a class whose mapping
information is applied to the entities that inherit from it. A mapped
superclass has no separate table defined for it.
So it says that the mapping information is applied to Entities, but it does not say that a MappedSuperclass is not allowed to extend another MappedSuperclass, so I believe you can use in your FornecedorSuper class the #MappedSuperclass annotation.
Q2. It is necessary to mark FornecedorPeças class with # Entity?
Yes, it is necessary.
I had put annotations on attributes and methods. For this reason was occurring exceptions.
Thanks for the help.

Find and delete an item from a collection

I have the following problem with a method of JPA.
I can not delete an item from a collection.
Actually, the method only works if it is not the last element inserted.
Where I'm wrong?
This is the class of my model:
#Entity
public class JobOffer {
#SequenceGenerator(name="JobOffer_Gen", sequenceName="JobOffer_Seq", initialValue=1, allocationSize=1)
#Id #GeneratedValue(generator="JobOffer_Gen") #Column(name="ID_JOBOFFER")
private Long id;
#Column
private String title;
...
#OneToMany
#JoinTable(joinColumns = #JoinColumn(name = "JOBOFFER_IDFK"), inverseJoinColumns = #JoinColumn(name = "LANGUAGE_IDFK"))
private Collection<Language> languages = new HashSet<Language>();
...
}
This is my method in JPA:
#Override
#Transactional
public void deleteLanguage(JobOffer joboffer, Long idLingua) throws BusinessException {
for(Language l : joboffer.getLanguages()){
if (l.getId() == idLingua){
joboffer.getLanguages().remove(l);
}
}
em.merge(joboffer);
}
What is the correct way to search for an item in a collection and delete in JPA?
This is the error that I get from the console:
21-ott-2013 18.22.27 org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [jobbook] in context with path [/jobbook] threw exception [Request processing failed; nested exception is java.util.ConcurrentModificationException] with root cause
java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at org.eclipse.persistence.indirection.IndirectList$1.next(IndirectList.java:571)
at it.univaq.mwt.j2ee.jobbook.business.impl.JPAJobOfferService.deleteLanguage(JPAJobOfferService.java:95)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
and then continues
You may try something like this:
#Override
#Transactional
public void deleteLanguage(JobOffer joboffer, Long idLingua) throws BusinessException {
Language language = em.createQuery("SELECT lang from Language lang where lang.jobOffer.id = :job_id", Language.class).setParameter("job_id", joboffer.getId()).getSingleResult();
if(language != null){
joboffer.getLanguages().remove(language);
}
}
Please note:
this is not tested
I assumed that your "Language" Entity has a reference to your JobOffer Entity. Although I do not know your domain, this may indicate a bad design
If the parameter joboffer is in detached state, then you have to reattach it to the current session (using em.merge()).
Edit: Adapted Query in response to the comment of DataNucleus.