Spring Data JPA date "between" query issue when using Date parameters - java

In my application, I am using Spring Data and hibernate as JPA provider to persist and read data.
I have top level Entity class:
#Entity
#Getter #Setter
#Table(name = "operation")
#Inheritance(strategy = InheritanceType.JOINED)
#EqualsAndHashCode(of = {"operationId"})
public abstract class Operation implements Serializable {
public static final int OPERATION_ID_LENGTH = 20;
#Id
#Column(name = "operation_id", length = OPERATION_ID_LENGTH, nullable = false, columnDefinition = "char")
private String operationId;
#Column(name = "operation_type_code")
#Getter(AccessLevel.NONE)
#Setter(AccessLevel.NONE)
private String operationTypeCode;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "begin_timestamp", nullable = false)
private Date beginTimestamp = new Date();
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "end_timestamp")
private Date endTimestamp;
#Column(name = "operation_number", length = 6, columnDefinition = "char")
private String operationNumber;
#Enumerated(EnumType.STRING)
#Column(name = "operation_status", length = 32, nullable = false)
private OperationStatus status;
#ManyToOne(optional = false)
#JoinColumn(name = "user_id")
private User user;
#ManyToOne
#JoinColumn(name = "terminal_id")
private Terminal terminal;
#Column(name = "training_mode", nullable = false)
private boolean trainingMode;
}
For inherited class I have corresponding repository:
public interface ConcreteOperationRepository extends JpaRepository<ConcreteOperation, String> {
#Query("SELECT o FROM ConcreteOperation o WHERE o.beginTimestamp BETWEEN :from AND :to AND o.status = :status AND o.terminal.deviceId = :deviceId AND o.trainingMode = :trainingMode")
Collection<ConcreteOperation> findOperations(#Param("from") Date startDay,
#Param("to") Date endDay,
#Param("status") OperationStatus status,
#Param("deviceId") String deviceId,
#Param("trainingMode") boolean trainingMode);
}
And I have integration test with following method:
#Transactional
#Test
public void shouldFindOperationByPeriodAndStatusAndWorkstationId() {
Date from = new Date(Calendar.getInstance().getTime().getTime());
List<String> terminalIds = loadTerminalIds();
List<OperationStatus> typeForUse = Arrays.asList(OperationStatus.COMPLETED,
OperationStatus.LOCKED, OperationStatus.OPEN);
int countRowsForEachType = 3;
int id = 100001;
for (String terminalId : terminalIds) {
for (OperationStatus status : typeForUse) {
for (int i = 0; i < countRowsForEachType; i++) {
concreteOperationRepository.save(createConcreteOperation(status, terminalId,
String.valueOf(++id)));
}
}
}
Date to = new Date(Calendar.getInstance().getTime().getTime());
for (String terminalId : terminalIds) {
for (OperationStatus status : typeForUse) {
Collection<ConcreteOperation> operations =
concreteOperationRepository.findOperations(from, to, status, terminalId, false);
assertEquals(countRowsForEachType, operations.size());
}
}
}
But this test fails when I using MySql database due to empty result (but passes when I switch to HSQLDB)
Also, this test passes if I put delay "Thread.sleep(1000)" for one second at the beginning of the test, just after the first line.
When I execute SQL from Hibernate log it gives me right result. What's wrong with my code?

In JPA, the Date requires a temporal hint. Normally, you could set the TemporalType when setting the JPA Query parameter:
query.setParameter("from", from), TemporalType.TIMESTAMP);
With Spring Data you need to use the #Temporal annotation, so your query becomes:
#Query("SELECT o FROM ConcreteOperation o WHERE o.beginTimestamp BETWEEN :from AND :to AND o.status = :status AND o.terminal.deviceId = :deviceId AND o.trainingMode = :trainingMode")
Collection<ConcreteOperation> findOperations(
#Param("from") #Temporal(TemporalType.TIMESTAMP) Date startDay,
#Param("to") #Temporal(TemporalType.TIMESTAMP) Date endDay,
#Param("status") OperationStatus status,
#Param("deviceId") String deviceId,
#Param("trainingMode") boolean trainingMode
);

I realized my problem. The problem was due to difference of precision between type of field in MySql (default timestamp precision cut of milliseconds) and Java date (with milliseconds)
I've altered my table:
ALTER TABLE transaction modify end_timestamp TIMESTAMP(6)
and that's solved my problem.

Related

org.hibernate.MappingException: Could not determine type for: java.util.List for Hierarchy Ref Cursor function result

I'm trying to call a procedure function in DB and to mapped the Hierarchy answer to entity class using hibernate.The entities that I wrote suppose to represent the result structure that is returned from a ref cursor function.
The result of the function has a property which is a list of objects and inside that object there is also a property that is also a list of another objects.
On application startup I get the MappingException as I wrote in the title above.
I tried to add the annotation #OneToMany but it is not working because it is not looking at tables in DB.
Again, the entities represent the function result and not select from table tables.
Someone has any idea of any annotation that could prevent from this exeception to araise in the application startup?
My Entities:
Main Entity that call to procedure function (rc):
#NamedNativeQuery(name = "GetDeliveryOptionsRC.runFunction",
query = "{ ? = call fn_get_delivery_options_rc_dev(:i_account_number,:i_work_order_number,:i_task_id,:i_task_type,:i_content_type_code,:i_sap_operator_code)}", resultClass = GetDeliveryOptionsRC.class,
hints = {#QueryHint(name = "org.hibernate.callable", value = "true")})
#Entity
#XmlRootElement(name = "GetDeliveryOptionsRC")
public class GetDeliveryOptionsRC implements Serializable {
#Id
private Long rownum;
#Column(name = "ACCOUNT_NUMBER")private Long accountNumber;
#Column(name = "TASK_TYPE")private Long taskType;
#Column(name = "CONTENT_TYPE")private String contentType;
#Column(name = "CONTENT_TYPE_CODE")private Long contentTypeCode;
#Column(name = "MESSAGE_CODE")private Long messageCode;
#Column(name = "MESSAGE_ERROR_CODE")private Long messageErrorCode;
#Column(name = "MESSAGE_ERROR_DESCR")private String messageErrorDescr;
#Column(name = "DELIVERY_OPTIONS")private List<DeliveryOptionsRC> deliveryOptions;
//getters & setters
}
Delivery Options Entity:
#Entity
#XmlRootElement(name = "DeliveryOptions")
public class DeliveryOptionsRC implements Serializable {
#Id
#Column(name = "DELIVERY_TYPE") private String deliveryType;
#Column(name = "DELIVERY_DESCR") private String deliveryDescr;
#Column(name = "PRICE") private Double price;
#Column(name = "EXISTS_FLAG") private String existFlag;
#Column(name = "IS_VALID") private String isValid;
#Column(name = "IS_SAP_ORDER") private String isSapOrder;
#Column(name = "IS_OTHER_ADDRESS") private String isOtherAddress;
#Column(name = "IS_SCHEDULE_NEEDED") private String isScheduledNeeded;
#Column(name = "PICKUP_SOURCE") private String pickupSource;
#OneToMany(targetEntity=ChargeJobs.class, mappedBy="deliveryOptionsRC", fetch=FetchType.EAGER)
#Column(name = "CHARGE_JOBES") private List<ChargeJobs> chargeJobs;
//getters & setters
}
Charge Jobs Entity:
#Entity
#XmlRootElement(name = "ChargeJobs")
public class ChargeJobs implements Serializable {
#Column(name = "JOB_OFFER_ID") private Long jobOfferId;
#Id
#Column(name = "JOB_CODE") private String jobCode;
#Column(name = "PRICE") private Double price;
#Column(name = "QUANTITY") private Long quantity;
//getters & setters
}
The RC function:
CREATE OR REPLACE FUNCTION YES_SIMPLE.fn_get_delivery_options_rc_dev (i_account_number NUMBER,
i_work_order_number NUMBER ,
i_task_id NUMBER ,
i_task_type NUMBER,
i_content_type_code NUMBER,
i_sap_operator_code NUMBER
)
RETURN sys_refcursor
is
out_ref sys_refcursor ;
ret tr.delivery_options_list_t;
xml sys.xmltype;
begin
ret:= TR.fn_get_delivery_options (p_account_number => i_account_number,
p_work_order_number =>i_work_order_number,
p_task_id =>i_task_id,
p_task_type =>i_task_type,
p_content_type_code =>i_content_type_code,
p_sap_operator_code => i_sap_operator_code) ;
open out_ref for
select ret.Account_number Account_number
,ret.Task_Type Task_Type,
ret.content_type content_type,
ret.content_type_code content_type_code,
ret.message_code message_code,
ret.message_error_code message_error_code,
ret.message_error_descr message_error_descr
,cursor(select DELIVERY_TYPE ,
DELIVERY_DESCR ,
PRICE ,
EXISTS_FLAG ,
IS_VALID ,
IS_SAP_ORDER ,
IS_OTHER_ADRESS ,
IS_SCHEDULE_NEEDED ,
PICKUP_SOURCE,
cursor(select * from(select * from(select * from table(select ret.delivery_options from dual) ))) charge_jobs
from table(select ret.delivery_options from dual) ) delivery_options
from dual;
return out_ref;
end;
Getting the following result:
ROWNUM 1
ACCOUNT_NUMBER 13
TASK_TYPE 1
CONTENT_TYPE OTT
CONTENT_TYPE_CODE 2
MESSAGE_CODE 98
MESSAGE_ERROR_CODE 98
MESSAGE_ERROR_DESCR
DELIVERY_OPTIONS <Cursor>
DELIVERY_TYPE T
DELIVERY_DESCR Tech
PRICE 0
EXISTS_FLAG N
IS_VALID Y
IS_SAP_ORDER N
IS_OTHER_ADRESS N
IS_SCHEDULE_NEEDED Y
PICKUP_SOURCE
CHARGE_JOBS <Cursor>
JOB_OFFER_ID 900310
JOB_CODE D80
PRICE 0
QUANTITY 1

GET transient field with zero int value in java spring data

We're making get requests through a controller. The model contains transient fields that are set in the controller. Only int fields that are not null or >0 are being returned by the controller. How can I allow a transient field to return a 0 value, as this is meaningful. In this case the transient fields are 'sentenceStart' and 'sentenceEnd'.
Controller:
#RequestMapping(value = "/{match_id}", method = RequestMethod.GET)
public Match getMatch(#PathVariable("match_id") long matchId) {
long start = System.currentTimeMillis();
LOGGER.info("REQUESTED RETRIEVAL OF MATCH WITH ID: " + matchId);
Match match = matchRepository.findOneById(matchId);
match.setActualText(matchRepository.getText(match.getId()));
match.setSentenceStart(matchRepository.getSentenceStart(match.getId()));
match.setSentenceEnd(matchRepository.getSentenceEnd(match.getId()));
match.setSentenceID(matchRepository.getSentenceId(match.getId()));
long end = System.currentTimeMillis();
LOGGER.info("DONE. TOOK " + (end - start) + " MILLISECONDS.");
return match;
} //getMatch()
Repository:
public interface MatchRepository extends JpaRepository<Match, Long>, JpaSpecificationExecutor<Match> {
#Query(value = "SELECT match_in_sentence_start FROM vTextMatch where match_id = :m_id LIMIT 1",
nativeQuery = true)
int getSentenceStart(#Param("m_id") long matchId);
#Query(value = "SELECT match_in_sentence_end FROM vTextMatch where match_id = :m_id LIMIT 1",
nativeQuery = true)
int getSentenceEnd(#Param("m_id") long matchId);
}
Model:
#Entity
#Table(name = "match_term")
#JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Match {
#Id
#GeneratedValue
#Column(name = "match_id", nullable = false)
private Long id;
#Column(name = "document_id", nullable = false)
private Long documentId;
#Column(name = "document_start")
private Integer documentStart;
#Column(name = "document_end")
private Integer documentEnd;
#Column(name = "is_meta", nullable = false)
private Boolean isMeta;
#Column(name = "date_inserted", nullable = false)
private Timestamp dateInserted;
#Transient
private String actualText;
#Transient
private int sentenceStart;
#Transient
private int sentenceEnd;
#Transient
private int sentenceID;
/*
|-------------------|
| AUXILIARY METHODS |
|-------------------|
*/
/*
|-------------------|
|SETTERS ANG GETTERS|
|-------------------|
*/
public int getSentenceStart() {
return sentenceStart;
}
public void setSentenceStart(int sentenceStart) {
this.sentenceStart = sentenceStart;
}
public int getSentenceEnd() {
return sentenceEnd;
}
public void setSentenceEnd(int sentenceEnd) {
this.sentenceEnd = sentenceEnd;
}
}
You should investigate line containing #JsonInclude(JsonInclude.Include.NON_EMPTY) - http://fasterxml.github.io/jackson-annotations/javadoc/2.0.0/com/fasterxml/jackson/annotation/JsonInclude.Include.html#NON_EMPTY
I would suggest slightly change your design and introduce some message type. You could avoid polluting your domain class with the not needed stuff.

Spring-Data-Jpa AuditingEntityListener createdDate updated upon saving existing entity

I have the following JPA Entity:
#EntityListeners(AuditingEntityListener.class)
#Entity
public class EntityWithAuditingDates {
#Id
#GeneratedValue
private Long id;
#Temporal(TemporalType.TIMESTAMP)
#CreatedDate
private Date createdDate;
#Temporal(TemporalType.TIMESTAMP)
#LastModifiedDate
private Date lastModified;
private String property;
// getters and setters omitted.
}
And the following CrudRepository:
#Service
public interface EntityWithAuditingDatesRepository extends CrudRepository<EntityWithAuditingDates, Long> {
}
And the following test:
#SpringApplicationConfiguration(classes = FooApp.class)
#RunWith(SpringJUnit4ClassRunner.class)
public class AuditingEntityListenerTest {
#Autowired
private EntityWithAuditingDatesRepository entityWithAuditingDatesRepository;
#Test
public void test() {
EntityWithAuditingDates entityWithAuditingDates = new EntityWithAuditingDates();
entityWithAuditingDates.setProperty("foo");
assertNull(entityWithAuditingDates.getCreatedDate());
assertNull(entityWithAuditingDates.getLastModified());
entityWithAuditingDatesRepository.save(entityWithAuditingDates);
assertNotNull(entityWithAuditingDates.getCreatedDate());
assertNotNull(entityWithAuditingDates.getLastModified());
assertEquals(entityWithAuditingDates.getLastModified(), entityWithAuditingDates.getCreatedDate());
entityWithAuditingDates.setProperty("foooo");
entityWithAuditingDatesRepository.save(entityWithAuditingDates);
assertNotEquals(entityWithAuditingDates.getCreatedDate(), entityWithAuditingDates.getLastModified());
}
}
The last condition fails. Shouldn't be the createdDate and the lastModifiedDate be different after updating the entity?
Thanks!
I faced the same issue but figured out a workaround for now. On #Column, I have set updatable=false to exclude create* fields on update.
#CreatedBy
#NotNull
#Column(name = "created_by", nullable = false, length = 50, updatable = false)
private String createdBy;
#CreatedDate
#NotNull
#Column(name = "created_date", nullable = false, updatable = false)
private ZonedDateTime createdDate = ZonedDateTime.now();
#LastModifiedBy
#Column(name = "last_modified_by", length = 50)
private String lastModifiedBy;
#LastModifiedDate
#Column(name = "last_modified_date")
private ZonedDateTime lastModifiedDate = ZonedDateTime.now();
It's not necessary to do another query to see fields updated. The repository's save method returns an object, which the documentation says that you should always use for further operations. The returned object should pass that last assertion. Try this:
entityWithAuditingDates = entityWithAuditingDatesRepository.save(entityWithAuditingDates);
If you retrieve the entity from the database after the update operation, the fields are set correctly. The test case below passes. Still, I wonder why they are set correctly on the first save operation, but then incorrectly upon the second. And you only get the correct information in the end when you retrieve the record from the database. I guess this is related to the hibernate cache.
#Test
public void test() throws InterruptedException {
EntityWithAuditingDates entityWithAuditingDates = new EntityWithAuditingDates();
entityWithAuditingDates.setProperty("foo");
assertNull(entityWithAuditingDates.getCreatedDate());
assertNull(entityWithAuditingDates.getLastModified());
entityWithAuditingDatesRepository.save(entityWithAuditingDates);
assertNotNull(entityWithAuditingDates.getCreatedDate());
assertNotNull(entityWithAuditingDates.getLastModified());
assertEquals(entityWithAuditingDates.getLastModified(), entityWithAuditingDates.getCreatedDate());
entityWithAuditingDates.setProperty("foooo");
Thread.sleep(1000);
entityWithAuditingDatesRepository.save(entityWithAuditingDates);
EntityWithAuditingDates retrieved = entityWithAuditingDatesRepository.findOne(entityWithAuditingDates.getId());
assertNotNull(retrieved.getCreatedDate());
assertNotNull(retrieved.getLastModified());
assertNotEquals(retrieved.getCreatedDate(), retrieved.getLastModified());
}

Ljava.lang.Object; cannot be cast when getting multipile fields Hibernate Repository

I fresh on spring technology and hibernate. Some days ago i create query getting all rows from table using repository. Today i was try get 2 fields from database. When i try read data form result list i getting Ljava.lang.Object; cannot be cast. This is my enity
#Entity
#Table(name = "cms")
public class Cms implements Serializable{
private static final long serialVersionUID = 1759832392332242809L;
#Id
#GeneratedValue
private Long id_page;
#Column(nullable = false)
private String title;
private String content;
#Temporal(TemporalType.DATE)
private Date createDate;
#Temporal(TemporalType.DATE)
private Date modifyDate;
#Column(nullable = true)
private int createBy;
#Column(nullable = true)
private int modifedBy;
#Column(nullable = false)
private Boolean inMenu;
public Cms(Long id_page, String title, String content, Date createDate,
Date modifyDate) {
this.id_page = id_page;
this.title = title;
this.content = content;
this.createDate = createDate;
this.modifyDate = modifyDate;
this.createBy = 1;
this.modifedBy = 1;
this.inMenu = true;
}
//getters setters to string
}
Repository
public interface CmsRepository extends Repository<Cms, Long>{
#Query("Select u.id_page,u.title from Cms u")
List<Cms> getMenu();
}
And takie this on controller
List<Cms> menus= cmsservice.menuAll();
System.out.println(menus.get(0).toString()); //error
Some one can explain me on example what is bad and how can fix this, this will helpfull for me.
Thats because you are retrieving individual properties - not the entire Cms Object.
I would use an instance of Query for this:
EntityManager em = emf.createEntityManager();
Query query = em.createQuery("Select u.id_page,u.title from Cms u");
List<Object[]> results = query.getResultList();
for(Object[] elements: results){
Long id = Long.valueOf(String.valueOf(elements[0]));
String title = String.valueOf(elements[1]);
}
SELECT NEW org.agoncal.javaee7.CustomerDTO(c.firstName, c.lastName, c.address.
street1)
FROM Customer c

HQL - comparing dates and objects

So I have the following code:
Query query = session.createQuery("select p.festivalDay from Performance p where p.startingTimestamp < :startingTimestamp " +
"and p.endingTimestamp> :endingTimestamp" +
"and p.artist= :artist");
query.setTimestamp("beginningTimestamp", cal.getTime());
cal.set(endHour, endMonth, endDay, endHour, endMinute);
query.setTimestamp("endingTimestamp", cal.getTime());
query.setParameter("artist", a);
For some reason this query is never returning any results, artist is an object from the Class Artist, festivalDay is one of FestivalDay.
Both the timestamp comparisons and artist comparisons seem to be failing (I tried the query with just the timestamps and I tried it with just the artist). ("a" is obviously an Artist object)
This is my model for Performance:
#Entity
#Table(name = "T_Performance")
public class Performance{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private Date startingTimestamp;
private Date endingTimestamp;
private Date soundCheckUur;
#ManyToOne
#Cascade(org.hibernate.annotations.CascadeType.ALL)
#JoinColumn(name = "podiumId")
private Podium podium;
#ManyToOne
#Cascade(org.hibernate.annotations.CascadeType.ALL)
#JoinColumn(name = "artistId", nullable = false)
private Artist artist;
#ManyToOne
#Cascade(org.hibernate.annotations.CascadeType.ALL)
#JoinColumn(name = "festivalDayId", nullable = false)
private FestivalDay festivalDay;
public Optreden(){
}
public Optreden(Date startingTimestamp, Date endingTimestamp, Date soundCheckHour) {
this.startingTimestamp = startingTimestamp;
this.endingTimestamp = endingTimestamp;
this.soundCheckHour = soundCheckHour;
}
public void setPodium(Podium podium) {
this.podium = podium;
}
public void setArtist(Artist artist) {
this.artist = artist;
}
public void setFestivalDay(FestivalDay festivalDay) {
this.festivalDay = festivalDay;
}
}
There is nothing wrong with my model, I have changed some names to their English versions so if you think you spot an error in the model I probably just forgot to translate it.
I fixed it! I forgot that December is the 11th month to Java and not 12th... :(

Categories

Resources