Parameter value [\] did not match expected type [java.lang.String (n/a)] - spring-data-jpa

Getting below exception for 2nd call onwards.We are using hibernate 5.6.6.Final
"message": "Parameter value [\] did not match expected type [java.lang.String (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [\] did not match expected type [java.lang.String (n/a)]",

You are facing a bug introduced in Hibernate 5.6.6.Final and fixed in 5.6.9.Final: https://hibernate.atlassian.net/browse/HHH-15142
Just upgrade your Hibernate version.

You must check if that field is an inner join, in that case you must go to the entity that is relating to your current entity.
Example:
#Table(name = "table_item")
public class DetalleSolicitudArchivo
You need get detail_id:
#ManyToOne
#JoinColumn(name = "table_detail_item_id")
private Carpeta carpeta;
#Column(name = "detail_item_id")
private Long detailItemId
I hope this you help.

Related

Saving value in Hibernate to another table than entity table

I have two tables bo_operator and hist_bo_operator_password. In bo_operator the id column is foreign key to hist_bo_operator_password and I can have many the same operator_id in hist_bo_operator_password and only one id in bo_operator.
My entity:
#Entity
#Table(name="bo_operator")
public class Operator implements Serializable
and that's how I am getting values from hist_bo_operator_password:
#ElementCollection
#CollectionTable(name="hist_bo_operator_password", joinColumns=#JoinColumn(name="id_operator"))
#Column(name="password")
public List<String> oldPasswords = new ArrayList<String>();
but when I'm trying to get only one value by:
#ElementCollection
#CollectionTable(name="hist_bo_operator_password", joinColumns=#JoinColumn(name="id_operator"))
#Column(name="password")
public String oldPassword;
I'm getting error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Illegal attempt to map a non collection as a #OneToMany, #ManyToMany or #CollectionOfElements: local.vlex.operator.model.Operator.oldPassword
and all I want to do is makeing an insert into hist_bo_operator_password by
operator.setOldPassword(oldPassword);. I think the problem is that it doesn't know which password take if there is many values for the same id.
How to achive it?
#Edit
I also tried:
#Table(name="bo_operator")
#SecondaryTable(name = "hist_bo_operator_password",pkJoinColumns=#PrimaryKeyJoinColumn(name="id_operator", referencedColumnName="id"))
I even found ORDER BY so:
#Column(name="password", table="hist_bo_operator_password")
#OrderBy("data_ins")
public String oldPassword;
but seems like there is no #Limit or something like this in JPA and I still have many values to the same id which cause error:
org.hibernate.HibernateException: Duplicate identifier in table for: [local.vlex.operator.model.Operator#1]
As you described at the first sentence you have one-to-many relationship
#ElementCollection
#CollectionTable(name="hist_bo_operator_password", joinColumns=#JoinColumn(name="id_operator"))
#Column(name="password")
#OrderBy("data_ins")
public List<String> oldPasswords = new ArrayList<String>();
Then add necessary getter
Optional<String> getPassword() {
return oldPasswords.size() > 0
? Optional.of(oldPasswords.get(0))
: Optional.empty();
}
And setter
void setPassword(String password) { // or maybe addPassword?
oldPasswords.add(password);
}
Why don't you create entity of hist_bo_operator_password?
Then you could have List of that entities (instead of just String List) and just add another object to List and save entity Operator.

Error: Parameter value did not match expected type

I am trying to retrieve a USER from my database using the ID in the WHERE clause. However I am receiving an error and my program is failing.
This is the error I'm receiving when I run my program:
ERROR [org.jboss.as.ejb3.invocation] (default task-19)
JBAS014134: EJB Invocation failed on component CustomerServiceBeanImpl
for method public abstract package.name.entity.ICustomer
package.name.bean.CustomerServiceBean.getCustomerById(long):
javax.ejb.EJBException: java.lang.IllegalArgumentException:
Parameter value [19533] did not match expected type [package.name.entity.User (n/a)]
Note: [19533] is a test value I used.
This is the method that is having the error in the CustomerServiceBeanImpl.java:
#Override
public Customer getCustomerById (final long id)
{
return Customer.getById (this.em, id);
}
This is the method that's being called by the component CustomerServiceBeanImpl:
public static Customer getById (final EntityManager em, final long id)
{
for (final Customer c : em.createNamedQuery ("Customer.getById", Customer.class)
.setParameter ("id", id).setMaxResults (1).getResultList ())
{
return c;
}
return null;
}
The name query is this:
#NamedQuery (name = "Customer.getById",
query = "SELECT o FROM gnf.Customer o WHERE o.user = :id")
In the Customer.java class itself the relevant column is this one:
#ManyToOne (fetch = FetchType.LAZY)
#JoinColumn (name = "user_id")
private User user;
Doing a quick check of my ERD the "id" column in my "customer" table has a data type of BIGINT. However I'm not sure if that matters. (PostgreSQL database by the way.)
How can I fix this error?
The WHERE clause in your named query seems to be the problem. The attribute user in your Customer.class is of type User and your query expects it to be a type compatible to long.
...
Parameter value [19533] did not match expected type [package.name.entity.User ...
So if you need more help on this it would be great to see the complete entities User and Customer.
It is happening because in your database the parameter will be a #oneToOne object and you have to call the id inside the Object so you have to give the query as following :
"select user from User user where user.customer.id=:param"

JPA Criteria api using IN expression with join

i have entity Request that have #ManyToMany Set<Region> regions, and Region entity have field region of type RegionEnum of enum type with constants of regions.
I need to create criteria to get requests, where its regions are in collection of RegionEnum;
In my choice:
List<RegionEnum> regs=...; // from method parameter
CriteriaBuilder cb=em.getCriteriaBuilder();
CriteriaQuery<Request> cq=cb.createQuery(Request.class);
Root<Request> from=cq.from(Request.class);
cq.where(cb.isTrue(from.join("regions").get("region").in(regs)));
return em.createQuery(cq).getResultList();
I have an java.lang.IllegalArgumentException: PREDICATE_PASSED_TO_EVALUATION (There is no English translation for this message.)
enum:
public enum RegionEnum {
CENTRAL("Центральный"),
SOUTH("Южный"),
NWEST("Северо-Западный"),
FEAST("Дальневосточный"),
SIB("Сибирский"),
URFO("Уральский"),
VOLGA("Волжский"),
NCAU("Северо-Кавказский");
private final String value;
private Region(String value) {
this.value=value;
}
public String value() {
return this.value;
}
}
is my criteria right and problem with enum? or criteria is bad?
I have faced with the same exception today so I tried to solve the problem.
Let's assume we have the following instances already initialized (as in your example):
CriteriaBuilder cb;
List<String> values;
Root<Entity> r; // where Entity has String name attribute
Now we can create a Predicate instance this way which is working using EclipseLink 2.6.2 library:
Predicate good = r.get("name").in(values);
But if we try to wrap the predicate into the cb.isTrue() method (as you did it) which require an "Expression<Boolean>" parameter like this:
Predicate wrong = cb.isTrue(r.get("name").in(values));
the mentioned exception PREDICATE_PASSED_TO_EVALUATION will be raised as you have received it even the expression has right syntax.
I think because Expression is an Ancestor of Predicate class but this just an idea. At least the exception message says something like this.
So just remove the cb.isTrue() wrapping and probably it will work for you as it works for me.

JPA: Map a Map<Enum, Entity>

i want to Map a map in JPA, but I get a Exception:
My java-code looks like that:
Issue.java:
#ElementCollection
#CollectionTable(
name="ISSUE_EMPLOYEE",
joinColumns=#JoinColumn(name="ISSUE_ID", referencedColumnName="ID")
)
#MapKeyColumn(name="EMPLOYEEPOSITION_ID")
#MapKeyConvert("myEnumConverter")
#JoinColumn(name="EMPLOYEE_ID")
private Map<EmployeePosition, Employee> namedEmployees = new Hashtable<EmployeePosition, Employee>();
EmployeePosition is a Enum andEmployee is a Entity.
I get this Exception :
Internal Exception: java.sql.SQLException: ORA-00904: "EMPLOYEES": invalid identifier
Error Code: 904
Call: INSERT INTO ISSUE_EMPLOYEE (ISSUE_ID, EMPLOYEES, EMPLOYEEPOSITION_ID) VALUES (?, ?, ?)
bind => [27, [B#18b85d, SERVICE]
It seems to ignore the #JoinColumn annotation and tries to insert the object in the DB.
What´s wrong with my mapping/Is it possible to match Entities like this?
As far as I understand, you need #OneToMany instead of #ElementCollection when value of a Map is an entity. Something like this:
#OneToMany
#JoinTable(name = "ISSUE_EMPLOYEE",
joinColumn = #JoinColumn(name = "ISSUE_ID"),
inverseJoinColumn = #JoinColumn("EMPLOYEE_ID"))
#MapKeyColumn(name="EMPLOYEEPOSITION_ID")
private Map<EmployeePosition, Employee> namedEmployees = new Hashtable<EmployeePosition, Employee>();
EDIT: The mapping above works fine in Hibernate, but doesn't work in EclipseLink. EMPLOYEEPOSITION_ID column in ISSUE_EMPLOYEE is created, but not used in queries. It happens not only with enum keys, but also with other primitive types.
It looks like a bug in EclipseLink. I can't find in in their Bugzilla, so perhaps it would be better to report it.

Entity bean 3.0 composite key issue

1: I have a table as shown below :
Name Null? Type
ATX_ID NOT NULL NUMBER(16)
ATX_GLM_CD NOT NULL NUMBER(5)
ATX_CRDR_FLG NOT NULL VARCHAR2(1)
ATX_AMT NOT NULL NUMBER(15,2)
ATX_STTS NOT NULL VARCHAR2(1)
ATX_TCM_ID NOT NULL NUMBER(16)
ATX_TXN_DT NOT NULL DATE
ATX_CRTE_BY NOT NULL VARCHAR2(30)
ATX_CRTE_DT NOT NULL DATE
The columns ATX_ID,ATX_GLM_CD and ATX_CRDR_FLG form a composite primary key.
2: I have created an entity bean class for the above table as follows :
#Entity
public class AcctngTxns implements Serializable {
private BigDecimal atxAmt;
private String atxStts;
private BigDecimal atxTcmId;
private Date atxTxnDt;
private String atxCrteBy;
private Date atxCrteDt;
#EmbeddedId
private AcctngTxnsPK acctngTxnsPK;
public AcctngTxns() {
//super();
}
/*getters and setters*/
}
#Embeddable
public class AcctngTxnsPK implements Serializable {
private long atxId;
private long atxGlmCd;
private String atxCrdrFlg;
private static final long serialVersionUID = 1L;
public AcctngTxnsPK() {
//super();
}
/*necessary overrides*/
}
3: /orm.xml/
http://java.sun.com/xml/ns/persistence/orm_1_0.xsd"
version="1.0">
4: /persistence.xml/
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
DataSource
com.nseit.ncfm2.data.ejb.entity.AcctngTxns
5: While accessing the entity bean via a session bean,I am getting the following exception :
<[weblogic.servlet.internal.WebAppServletContext#1a1bc8f - appName: '_auto_generated_ear_', name: 'AWebApp', context-path: '/AWebApp', spec-version: '2.5'] Servlet failed with Exception
javax.ejb.EJBException: EJB Exception: ; nested exception is:
org.apache.openjpa.persistence.ArgumentException: Fields "com.nseit.ncfm2.data.ejb.entity.AcctngTxns.acctngTxnsPK" are not a default persistent type, and do not have any annotations indicating their persistence strategy. If you do not want these fields to be persisted, annotate them with #Transient.
at weblogic.ejb.container.internal.RemoteBusinessIntfProxy.unwrapRemoteException(RemoteBusinessIntfProxy.java:105)
at weblogic.ejb.container.internal.RemoteBusinessIntfProxy.invoke(RemoteBusinessIntfProxy.java:87)
at $Proxy127.gottaAccessEntity3(Unknown Source)
at jsp_servlet.__result.jspService(_result.java:115)
at weblogic.servlet.jsp.JspBase.service(JspBase.java:34)
Truncated. see log file for complete stacktrace
org.apache.openjpa.persistence.ArgumentException: Fields "com.nseit.ncfm2.data.ejb.entity.AcctngTxns.acctngTxnsPK" are not a default persistent type, and do not have any annotations indicating their persistence strategy. If you do not want these fields to be persisted, annotate them with #Transient.
at org.apache.openjpa.persistence.PersistenceMetaDataFactory.validateStrategies(PersistenceMetaDataFactory.java:399)
at org.apache.openjpa.persistence.PersistenceMetaDataFactory.load(PersistenceMetaDataFactory.java:205)
at org.apache.openjpa.meta.MetaDataRepository.getMetaDataInternal(MetaDataRepository.java:474)
at org.apache.openjpa.meta.MetaDataRepository.getMetaData(MetaDataRepository.java:294)
at org.apache.openjpa.kernel.BrokerImpl.newObjectId(BrokerImpl.java:1114)
Truncated. see log file for complete stacktrace
7: Certainly,I do not want the primary key fields to be updated.
8: I tried to figure out the implementation of the below points mentioned in JPA documentation :
A composite primary key must be represented and mapped to multiple fields or properties of the entity class, or must be represented and mapped as an embeddable class.
If the class is mapped to multiple fields or properties of the entity class, the names and types of the primary key fields or properties in the primary key class must match those of the entity class.
8: Please help me in resolving the issue.
Thanks !
I found a solution by trial-and-error method. It seems that with JPA 1.0,it is necessary to mention the embedded-id in orm.xml file as follows :
Thanks.