Spring JPA - "Invalid column index" when inserting in DB - java

I am facing an issue when trying to insert 1 record in a parent table (DART_ORDER) and 2 records in a child table connected to the parent (DART_ODATE). Those 2 tables are linked by a OneToMany-ManyToOne relation as follows:
#Getter
#Setter
#ToString
#NoArgsConstructor
#Accessors(chain = true)
#Entity
#Table(
name = "DART_ORDER",
schema = Constants.ORACLE_DB_SCHEMA
)
public class OrderDAO implements Serializable {
#NotNull
private String WHY;
#NotNull
private String WHO;
#Id
#NotNull
private String ORDERID;
private String DESCRIPTION;
#NotNull
private String STATUS;
#NotNull
private String COUNTRY;
#NotNull
private String TYPE;
#NotNull
private String REPETITION;
private String REF_REFORDERID;
#OneToMany(mappedBy = "ORDER", cascade = CascadeType.ALL)
#OrderBy("DID ASC")
#ToString.Exclude
private List<OrderDateDAO> DATES;
#OneToMany(mappedBy = "ORDER", cascade = CascadeType.ALL)
#OrderBy("DID ASC")
#ToString.Exclude
private List<OrderDocDAO> DOCS;
}
#Getter
#Setter
#ToString
#NoArgsConstructor
#Accessors(chain = true)
#Entity
#Table(
name = "DART_ODATE",
schema = Constants.ORACLE_DB_SCHEMA,
indexes = #Index(
name = "PK_DART_ODATE",
columnList = "REF_ORDERID, ODTTYPE",
unique = true
)
)
#IdClass(OrderDateDAO.class)
public class OrderDateDAO implements Serializable {
#NotNull
private String WHY;
#NotNull
private String WHO;
#Id
#NotNull
private String REF_ORDERID;
#Id
#NotNull
private String ODTTYPE;
#NotNull
private LocalDate ODATE;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "REF_ORDERID", referencedColumnName = "ORDERID", insertable = false, updatable = false)
#ToString.Exclude
private OrderDAO ORDER;
}
When I try saving a record giving a complete OrderDAO object, I get the following exception:
Caused by: java.sql.SQLException: Invalid column index
at oracle.jdbc.driver.OraclePreparedStatement.setFormOfUseInternal(OraclePreparedStatement.java:10470)
at oracle.jdbc.driver.OraclePreparedStatement.setFormOfUseInternal(OraclePreparedStatement.java:10451)
at oracle.jdbc.driver.OraclePreparedStatement.setString(OraclePreparedStatement.java:5240)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.setString(OraclePreparedStatementWrapper.java:255)
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.setString(HikariProxyPreparedStatement.java)
at org.hibernate.type.descriptor.sql.VarcharTypeDescriptor$1.doBind(VarcharTypeDescriptor.java:46)
at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:73)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:276)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:271)
at org.hibernate.type.ComponentType.nullSafeSet(ComponentType.java:340)
at org.hibernate.persister.entity.AbstractEntityPersister.dehydrateId(AbstractEntityPersister.java:3121)
at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:3079)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3372)
... 87 more
By enabling the logs for Hibernate's SQL statements, I noticed that the insert one for the DART_ODATE table has the correct number of ? symbols as parameters, but, for no apparent reason, the log immediately below shows 7 parameters passed, instead of 6, among which 1 seems to be null.
2022-05-03T13:27:24,074 TRACE [http-nio-8080-exec-5] o.h.t.d.s.BasicBinder: binding parameter [4] as [VARCHAR] - [null]
I don't honestly know why it keeps considering 1 parameter in addition, since the only additional mapping set in the DAO is the JoinColumn one...
Besides, I already tried upgrading both my SpringBoot and Hibernate Validator versions to the latest ones, but I still got the error.
Has any of you experienced the same issue?
Thank you.
Regards,
A.M.

I finally managed to understand my mistake!
The issue was related to a wrong use of the JoinColumn annotation.
Basically, I removed the ORDER attribute within the *OrderDateDAO", and changed the parent DATES attribute as follows:
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "REF_ORDERID", referencedColumnName = "ORDERID")
#ToString.Exclude
private List<OrderDateDAO> DATES;
Using a uni-directional relation, the INSERT statement worked like a charm! :-)

Related

Spring JPA - referencedColumnNames [...] not mapped to a single property - Issue with #IdClass

I am facing the issue reported as subject when dealing with the following example:
[other irrelevant annotations]
#IdClass(KeyDAO.class)
public class KeyDAO implements Serializable {
#Id
#NotNull
private String KEYGROUP;
#Id
#NotNull
private String KEYVAL;
[...]
#OneToMany(mappedBy = "KEY")
#ToString.Exclude
private List<OrderDateDAO> ODATES;
}
[other irrelevant annotations]
#IdClass(OrderDateDAO.class)
public class OrderDateDAO implements Serializable {
[...]
#Id
#NotNull
private String ODTTYPE;
[...]
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumnsOrFormulas({
#JoinColumnOrFormula(formula = #JoinFormula(value = Constants.DART_KEYGROUP_ODTTYPE, referencedColumnName = "KEYGROUP")),
#JoinColumnOrFormula(column = #JoinColumn(name = "ODTTYPE", referencedColumnName = "KEYVAL", insertable = false, updatable = false))
})
#ToString.Exclude
#OrderBy("ORDERASC ASC")
private KeyDAO KEY;
}
Basically, OrderDateDAO shall be joined with KeyDAO, and both use an #IdClass annotation. By following the tips on this site, I decided to use a JoinColumnsOrFormulas annotation, because:
the real column to join is ODTTYPE <-> KEYVAL
the KEY table shall be narrowed down by setting a specific fixed value for the KEYGROUP column
Currently, I am getting the following exception:
Caused by: org.hibernate.AnnotationException: referencedColumnNames(KEYGROUP, KEYVAL) of eu.unicredit.dtm.dtm_be.dao.oracle.OrderDateDAO.id.KEY referencing eu.unicredit.dtm.dtm_be.dao.oracle.KeyDAO not mapped to a single property
I have tried several other options, but still the error occurs.
Any help or suggestions here?
Thank you.
Regards,
A.M.

Spring Boot: Could not locate field name [companyId] on class [...Entity]

I have a question:
Here is my entity:
public class CompanyBindingEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "BINDING_ID", nullable = false)
private int companyBindingId;
#NotNull
#Embedded
#Valid
private CompanyEntity company;
....
}
Here is CompanyEntity:
#NoArgsConstructor
#AllArgsConstructor
#Embeddable
#Builder
#Data
public class CompanyEntity {
#Id
#NotNull
#Column(name = "COMPANY_ID")
private Integer companyId;
#NotNull
#Column(name = "COMPANY_NAME")
private String companyName;
}
And I want to implement
findByCompanyId(int companyId)
method in my service and repository. But I am receiving this error:
Could not locate field name [companyId] on class [...Entity]
because the companyId is inside CompanyEntity, not in CompanyBindingEntity. I need to find a way about how to solve this. Am I missing a special annotation to search for a nested element?
Thanks a lot for reading!
First, you need to define an association between CompanyBindingEntity and CompanyEntity, for example:
#NotNull
#Embedded
#Valid
#OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetchType = FetchType.EAGER)
#JoinColumn(name = "COMPANY_ID")
private CompanyEntity company;
Then in the table that holds CompanyBindingEntity define a foreign key to bind "COMPANY_ID" to the ID for CompanyEntity.

Spring Data JPA / Hibernate ManyToMany relation is always empty

I've faced with an issue, I've declared the bidirectional #ManyToMany relation between my entities, but when I try to perform the select by repository, the #ManyToMany collection is always empty.
There is an example of my entities:
#Data
#EqualsAndHashCode
#Entity
#Table(name = "provider", schema = "debt")
public class ProviderEntity {
#Id
#Column(name = "provider_id")
private String providerId;
#Column(name = "external_provider_id")
private String externalProviderId;
private String description;
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(
name = "provider_supported_driver", schema = "debt",
joinColumns = #JoinColumn(name = "provider_id", foreignKey = #ForeignKey(name = "FK_PSD_TO_P")),
inverseJoinColumns = #JoinColumn(name = "driver_id", foreignKey = #ForeignKey(name = "FK_PSD_TO_D"))
)
private Set<DriverEntity> drivers = new HashSet<>();
}
#Data
#EqualsAndHashCode
#Entity
#Table(name = "driver", schema = "debt")
public class DriverEntity {
#Id
#Column(name = "driver_id")
private String driverId;
#Enumerated(EnumType.STRING)
private DriverType type;
private String description;
#ManyToMany(mappedBy = "drivers")
private Set<ProviderEntity> provider = new HashSet<>();
}
Also, I've enabled the SQL query logs, that hibernate generates, when I run it, the query works well.
I've tried different guides and answers for the same issues, but I've no result with them.
What's the reason for this behavior? Maybe has somebody any ideas?
I've found the reason for this issue and the problem is in the primary keys of my tables, they aren't generated by sequence or some different way, as I understand Hibernate doesn't understand how to map this columns

Repeated column in mapping for entity with #ManyToOne

I have two entities which is giving me error on creation of datasource
Entity1
#NoArgsConstructor
#Entity
#Table(name = "person_details")
public class PersonDetails {
#Id
private String pid;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "exist_flag")
private String existFlag;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinColumn(name = "pid", nullable = false)
private List<AddressDetails> addressDetails;
}
Entity 2 | EDIT 1
#Data
#NoArgsConstructor
#Entity
#Table(name = "address_details")
public class AddressDetails {
private String street;
#Column(name = "address_exist_flag")
private String addressExistFlag;
#ToString.Exclude
#EqualsAndHashCode.Exclude
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "pid", insertable = false, updatable = false)
private PersonDetails personDetails;
}
Getting error as below:
I am getting error as "No identifier specified for entity: AddressDetails".
How to resolve in such case? Can we use spring data jpa having OneToMany mapping in such case where one entity do not have primary key ?
The error you are getting is because you are using the same column name for 2 different columns.
#Id
private String pid;
and
#JoinColumn(name = "pid"
means that you want both your id column and your foreign key column to be named "pid", hence the error. I would suggest using a name like "addressDetailsFk" for the JoinColumn attribute.

Spring boot application Creating Two Database rows

I have a spring boot application with MySQL database. Below method is creating medication's two rows with same fields.
#Override
#Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public MedicationGroup save(MedicationGroup medicationGroup) {
return medicationRepository.save(medicationGroup);
}
Medication Group Entity:
#Getter
#Setter
#Table(name = "medication_group")
#Entity
#Builder
#NoArgsConstructor
#AllArgsConstructor
public class MedicationGroup extends AbstractEntity implements Persistable {
private static final long serialVersionUID = 2948809916398284974L;
private Short type;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "patient_id", nullable = false, updatable = false, insertable = false)
private Patient patient;
#Column(name = "patient_id")
private Long patientId;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "medicationGroup", cascade = CascadeType.ALL)
private List<Prescription> prescriptions;
}
Below rows are created into database :
Its not happening continually it will happen any time unable to find reason.
Are you sure the method is not called twice. Try using primary key in one of the fields, so that duplicate data is not stored in the database.

Categories