The object of class oracle.sql.TIMESTAMPTZ from mapping could not be converted to class java.util.Date - oracle

I am facing an issue in eclipselink with TIMESTAMPTZ. There is a column in table which have timestamp and timezone. When I run my program I am getting exception.
I have tried everything already on stackOverflow with similar issues and even on the below link.
https://www.eclipse.org/forums/index.php/t/443917/
Query q = em.createNativeQuery("SELECT * FROM MY_Schema.MyTable MT WHERE MT.START_DT = (SELECT MAX(START_DT) FROM MY_Schema.MyTable)",MyTable.class);
#Entity
#Table(name = "MyTable", schema = "MY_Schema")
public class MyTable implements Serializable {
#EmbeddedId
private MyTableId id;
#Embeddable
public class MyTableId implements Serializable {
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "END_DT")
private Calendar endTime;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "START_DT")
private Calendar startTime;
Error message:
5943 [Default Executor-thread-32] ERROR com....MyClass -
javax.persistence.PersistenceException: Exception [EclipseLink-3002]
(Eclipse Persistence Services - 2.6.8.WAS-v20181218-0accd7f):
org.eclipse.persistence.exceptions.ConversionException Exception
Description: The object [oracle.sql.TIMESTAMPTZ#d1f0d927], of class
[class oracle.sql.TIMESTAMPTZ], from mapping
[org.eclipse.persistence.mappings.DirectToFieldMapping[startTime--Y_Schema.MyTable.START_DT]]
with descriptor [RelationalDescriptor(com.....MyTableId -->
[DatabaseTable(MY_Schema.MyTable)])], could not be converted to [class
java.util.Date]. at
org.eclipse.persistence.internal.jpa.QueryImpl.getSingleResult(QueryImpl.java:551)

Related

Can't access a property of a Embedded class via JPA

#Entity
#EntityListeners(AuditingEntityListener.class)
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "TIPO_CONTRATO", discriminatorType = DiscriminatorType.STRING)
#JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
public class Contrato extends AuditorEntity implements Serializable, Clonable {
#Column(name = "CIF_NIF")
#JsonView(Views.Buscador.class)
#JsonProperty("cifNif")
private String cifNif;
#Column(name = "NOMBRE_SOCIEDAD_PERSONA")
#JsonView(Views.Buscador.class)
private String nombreSociedadPersona;
}
And i have this Embeddable class called CuentaBancaria from Contrato table:
#Embeddable
public class CuentaBancaria implements Serializable {
private static final long serialVersionUID = 6835775213299596371L;
#Column(name = "TITULAR_CUENTA")
#JsonView(Views.Completo.class)
private String titularCuenta;
}
In ContratoRepository i'm trying doing a JPA Query finding the "titularCuenta" field of Cuenta Bancaria finding by the cifNif field of Contrato. But it's not working. What can i do to solve this?
#Query(value="SELECT c.CuentaBancaria.titularCuenta FROM Contrato c WHERE c.cifNif= ?1 AND c.nombreSociedadPersona IS NOT NULL AND ROWNUM = 1")
public String getNombreLegalCliente(String cifNif);
The error which is throwing:
Caused by: org.hibernate.QueryException: could not resolve property:
CuentaBancaria of: com.xxxx.Contrato
You're missing CuentaBancaria field in Contrato class. That's why JQL complains.
Add the field in the class with #Embedded annotation:
public class Contrato extends AuditorEntity implements Serializable, Clonable {
#Embedded
private CuentaBancaria cuentaBancaria;
}
And fix the JQL expression to:
#Query(value="SELECT c.cuentaBancaria.titularCuenta FROM Contrato c WHERE c.cifNif= ?1 AND c.nombreSociedadPersona IS NOT NULL AND ROWNUM = 1")
public String getNombreLegalCliente(String cifNif);
Yes, since your class [ CuentaBancaria ] is annotated with #Embeddable, it needs to be embedded in the parent class in this case [ Contrato ] with #Embedded.
Then, harnessing Spring Data JPA query Lookup strategies, you can access property fields of your embedded class with ease or you could still go by the #Query() approach
Query lookup Strategy from Spring documentation
Sample demo code with your problem with a minimal implementation:
Entity-Class
--------------
#Entity
public class Contrato{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long contratoId;
#Column(name = "CIF_NIF")
private String cifNif;
#Column(name = "NOMBRE_SOCIEDAD_PERSONA")
private String nombreSociedadPersona;
//we call the embeddable class in this parent class with #Embedded annotation
#Embedded
private CuentaBancaria cuentaBancaria
}
Embeddable-Class
-----------------
#Embeddable
public class CuentaBancaria{
#Column(name = "TITULAR_CUENTA")
private String titularCuenta;
}
Now in your ContratoRepository class, we could have
#Repository
public interface ContratoRepository extends CrudRepository<Contrato, Long> {
Optional<Contrato> findByCuentaBancariaTitularCuenta(String cifNif);
}
which interprets to JPQL snippet:
c.cuentaBancaria.titularCuenta FROM Contrato c WHERE c.cifNif= ?1
NOTE: Notice the query method name matches the exact names in the classes and their corresponding fields, preceded by findBy

Why can't I access embedded properties in a mapper?

I have the following embedabble
#Data
#Embeddable
public class BaseEntity {
#CreatedDate
#Column(name = "created_date")
private LocalDateTime createdDate;
#CreatedBy
#Column(name = "created_by")
private String createdBy;
}
Which I embed into my entity like so
#Entity
#Data
#NoArgsConstructor
#Table(name = "participant")
public class Participant {
#Id
#GeneratedValue
private UUID id;
#Embedded
private BaseEntity baseEntity;
}
And in my mapper I want to access the embedded properties of the Participant like so
#Mapping(target = "createdDate", source = "participant.createdDate")
ParticipantDto entityToDto(Participant participant);
But I get the following error message
error: The type of parameter "participant" has no property named "createdDate".
As mapping source I tried participant.basicEntitity.createdDate which also results in the same error message as well as not specifying any mapping so mapstruct can automap, which also results in the property not found error message

Getting BeanCreationException: Unknown entity name: int : Hibernate with JPA

I am new to Hibernate, I have written a entity class as below as per the table definition:
#Embeddable
class APK implements Serializable {
private String bId;
private int version; <---THIS IS CAUSING PROBLEM
}
#Entity
#Table(name = "a")
public class A implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private APK aPK;
#MapsId("bId")
#ManyToOne
#JoinColumn(name = "b_id", referencedColumnName = "id")
private B b;
#MapsId("version")
#Column(name = "version")
private int version;
#Column(name = "name")
private String name;
}
While, I am starting the server, I am getting following exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'entityManagerFactory' defined in class path resource
[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation
of init method failed; nested exception is org.hibernate.AnnotationException: Unknown entity
name: int
In table definition type of version is int. But to fix this I even tried to change the version type to Long, Integer but always I am getting similar error. Any idea how should I fix this issue ?
Remove #MapsId("version") annotation from private int version;, cause int is not an Entity. Refer here for more details.

How to write query for many to one mapped entity in JpaRepository

I have two entities and mapped those using many-to-one annotation but after writing a query for find object using another table id I got an error when I commented out that line and method called to that application work but I want to implement that functionality and please help me
These are my entity classes:
#Entity
#Table(name = "Contract")
public class Contract implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "contractId")
private long contractId;
#Column(name="start_date")
private Date st_date;
#Column(name="end_date")
private Date end_date;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "hotel_id", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
#JsonIgnore
private Hotel hotel;
// getters and setters
Second entity
#Entity
#Table(name="Hotel")
public class Hotel {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="hotel_id")
private long hotel_id;
#Column(name="hotel_name")
private String hotel_name;
#Column(name="hotel_location")
private String hotel_location;
#Column(name="hotel_email")
private String hotel_email;
#Column(name="hotel_telephone")
private String hotel_telephone
// getters and setters
My contract service class
#Service
public class ContractService {
#Autowired
private ContractRepository contractRepository;
#Autowired
private HotelRepository hotelRepository;
public List<Contract> getAllContracts(){
return contractRepository.findAll();
}
public List<Contract> findByHotelId(Long hotelId,Pageable pageable){
return contractRepository.findByHotelId(hotelId, pageable);
}
public ResponseEntity<?> deleteContract(Long hotelId, Long contractId)
{
return contractRepository.findByIdAndHotelId(contractId,
hotelId).map(Contract -> {
contractRepository.delete(Contract);
return ResponseEntity.ok().build();
}).orElseThrow(() -> new ResourceNotFoundException("Comment not found
with ContractId " + contractId + " and hotelId " + hotelId));
}
My contract repository
#Repository
public interface ContractRepository extends JpaRepository<Contract, Long> {
List<Contract> findByHotelId(Long hotelId, Pageable pageable);
Optional<Contract> findByIdAndHotelId(Long id, Long hotelId);
}
I got this error when running my project
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'contractController': Unsatisfied dependency expressed through field 'contractService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'contractService': Unsatisfied dependency expressed through field 'contractRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contractRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List com.sunTravel.sunRest.repository.ContractRepository.findByHotelId(java.lang.Long,org.springframework.data.domain.Pageable)! No property id found for type Hotel! Traversed path: Contract.hotel.
First Solution: based on your stack trace, Spring data is looking for id variable (primary key) in your Hotel class. So please change private long hotel_id; to private long id;
Another solution (no need to change anything just add your own query):
write your own JPA query using #Query.
Example:
#Query("SELECT contract from Contract as contract where contract.hotel.hotel_id = :hotelId")
List<Contract> findByHotelId(Long hotelId, Pageable pageable);
You should rename your Primary Key from hotel_id to id then only your repository method will work.
#Entity
#Table(name="Hotel")
public class Hotel {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="hotel_id")
private long id;
#Column(name="hotel_name")
private String hotel_name;
#Column(name="hotel_location")
private String hotel_location;
#Column(name="hotel_email")
private String hotel_email;
#Column(name="hotel_telephone")
private String hotel_telephone
// getters and setters

Filter Criteria by attribute with #Convert

I have a simple class with a list of Strings and this list is converted to be one column in db with #Convert and now i'm trying to create a criteria based on type attrbute.
#Entity(name = "my_table")
public class MyTable implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column
#Convert(converter = StringListConverter.class)
private List<String> type;
}
and criteria :
c2.add(Restrictions.ilike("type", matchValue, MatchMode.ANYWHERE));
but I got this exception :
org.springframework.orm.jpa.JpaSystemException: Error attempting to apply AttributeConverter; nested exception is javax.persistence.PersistenceException: Error attempting to apply AttributeConverter
*all entries have a value and I use a psql db
It is not possible right now with Hibernate.
Please see the bug ticket: https://hibernate.atlassian.net/browse/HHH-9991

Resources