'Using Enum values in @Query JPQL and @CreationTimestamp hibernate
I am stuck with some problem about using JPQL with spring data
Here is my code snippets
@Entity
@Table
//...
public class Parent {
@Id
private String id;
@Enumerated(EnumType.STRING)
private Status status;
@CreationTimestamp
private OffsetDateTime createTs;
@UpdateTimestamp
private OffsetDateTime updateTs;
@OneToOne(mappedBy = "parent", cascade = CascadeType.MERGE, optional = false)
@PrimaryKeyJoinColumn
private Child child;
//... getters setters and constructors
}
@Entity
@Table
//...
public class Child {
@Id
// is primary key in child table and refers to parent.id
private String parentId;
@OneToOne(fetch = FetchType.LAZY, optional = false)
@MapsId
@JoinColumn(name = "parent_id", referencedColumnName = "id")
private Parent parent;
//... getters setters and constructors
}
@Repository
public class ParentRepository extends CRUDRepository<Parent, String> {
@Query(value =
"from Parent p " +
"left join Child c " +
"where p.status in ('status1','status2') " +
"and p.updateTs between :fromUpdateTS and :toUpdateTS")
List<Parent> customQuery(OffsetDateTime fromUpdateTS, OffsetDateTime toUpdateTS);
}
So my first problem is that in native sql this custom query works just fine but once i needed to switch to JPQL, i figured out that it seems like there is no way to use IN clause with Enum collections, that is not passed as a named parameter in the query and this query doesn't work. And same thing is about 'between' keyword for timestamps, i tried < and > instead of 'between', but didn't succeed. So question is - what is proper way to construct such a query using JPQL in @Query annotation for CrudRepository. I would rather avoid adding additional named parameter like ':statuses' cause it doesn't make any sense at all.
Second question is when i use parentRepository.save(parent) everything works good and timestamps is being created correctly by hibernate. But! When i just remove 'optional = false' from One-to-one mapping in Parent entity class, it starts giving me an error from database about null value of not null field create_ts (createTs in java class). And i am extremely confused with the fact that mandatoriness of the related entity as a hint for hibernate affects timestamp generation of completely other field. I know that 'optional' tells hibernate either to load related entity or not for setting correct proxy and lazy loading doesn't work with optional one-to-one mappings.
Could someone explain this behaviour to me please? I would really appreciate it
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|