I'm currently a little blocked with this and I can't see it clearly.
So I hope one of you have good idea's to help me.
The important code at the moment :
#Entity
#Table(name = "T_NOTA_RECIPIENT")
public class NotaRecipient extends PersistentEntity {
#Id
#Column(name = "NOTA_RECIPIENT_SID")
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column(name = "STATUS", insertable = true, updatable = true)
#Enumerated(EnumType.STRING)
private Status status = Status.NEW;
#ManyToOne
#JoinColumn(name = "NOTA_SID", referencedColumnName = "NOTA_SID", nullable = false)
private Nota nota;
#ManyToOne
#JoinColumn(name = "CREATOR_OFFICE_SID", referencedColumnName = "OFFICE_SID", nullable = false)
private Office creator;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "notaRecipient")
private Set<FollowUp> followUps;
...
}
Now, actually I don't want to load all the FollowUp who are in the DB but just the one of the current user.
But the problem is that I want to include the FollowUp so I can do database paging query.
We use hibernate, Spring Data and Query DSL with BooleanBuilder to "refine" our search.
I was thinking of using #Formula but this need to be a constant String so I can't include current userId in that.
Second solution could be setting the FollowUp as #Transient and fetch it myself in the DB and set it in mine service.
Problem here is that I can't use it as filter then or ordering by it.
#Formula doesn't have so much documentation, so is it possible to make a #Transient user and use that in the #Formula?
I asked some colleagues but they couldn't help me.
So then it's the time for asking here.
I can get the current user in the API, so that's no problem.
Anybody have alternative solutions?
You can define a mapping with expression
#JoinColumnOrFormula(formula=#JoinFormula(value="(SELECT f.id
FROM follow_up_table f
WHERE f.nota_id=id
and f.user_id={USER_ID})",
referencedColumnName="...")
And then add hibernate interceptor (see the example) and change the SQL on fly replacing {USER_ID} with real value in the
/**
* Called when sql string is being prepared.
* #param sql sql to be prepared
* #return original or modified sql
*/
public String onPrepareStatement(String sql);
Related
I need to load the Post entities along with the PostVote entity that represents the vote cast by a specific user (The currently logged in user). These are the two entities:
Post
#Entity
public class Post implements Serializable {
public enum Type {TEXT, IMG}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
protected Integer id;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "section_id")
protected Section section;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "author_id")
protected User author;
#Column(length = 255, nullable = false)
protected String title;
#Column(columnDefinition = "TEXT", nullable = false)
protected String content;
#Enumerated(EnumType.STRING)
#Column(nullable = false)
protected Type type;
#CreationTimestamp
#Column(nullable = false, updatable = false, insertable = false)
protected Instant creationDate;
/*accessor methods*/
}
PostVote
#Entity
public class PostVote implements Serializable {
#Embeddable
public static class Id implements Serializable{
#Column(name = "user_id", nullable = false)
protected int userId;
#Column(name = "post_id", nullable = false)
protected int postId;
/* hashcode, equals, getters, 2 args constructor */
}
#EmbeddedId
protected Id id;
#ManyToOne(optional = false)
#MapsId("postId")
protected Post post;
#ManyToOne(optional = false)
#MapsId("userId")
protected User user;
#Column(nullable = false)
protected Short vote;
/* accessor methods */
}
All the associations are unidirectional #*ToOne. The reason I don't use #OneToMany is because the collections are too large and need proper paging before being accessed: not adding the #*ToManyassociation to my entities means preventing anyone from naively doing something like for (PostVote pv : post.getPostVotes()).
For the problem i'm facing right now I've come with various solutions: none of them looks fully convincing to me.
1° solution
I could represent the #OneToMany association as a Map that can only be accessed by key. This way there is no issue caused by iterating over the collection.
#Entity
public class Post implements Serializable {
[...]
#OneToMany(mappedBy = "post")
#MapKeyJoinColumn(name = "user_id", insertable = false, updatable = false, nullable = false)
protected Map<User, PostVote> votesMap;
public PostVote getVote(User user){
return votesMap.get(user);
}
[...]
}
This solution looks very cool and close enough to DDD principles (i guess?). However, calling post.getVote(user) on each post would still cause a N+1 selects problem. If there was a way to efficiently prefetch some specific PostVotes for subsequent accesses in the session then it would be great. (Maybe for example calling from Post p left join fetch PostVote pv on p = pv.post and pv.user = :user and then storing the result in the L1 cache. Or maybe something that involves EntityGraph)
2° solution
A simplistic solution could be the following:
public class PostVoteRepository extends AbstractRepository<PostVote, PostVote.Id> {
public PostVoteRepository() {
super(PostVote.class);
}
public Map<Post, PostVote> findByUser(User user, List<Post> posts){
return em.createQuery("from PostVote pv where pv.user in :user and pv.post in :posts", PostVote.class)
.setParameter("user",user)
.setParameter("posts", posts)
.getResultList().stream().collect(Collectors.toMap(
res -> res.getPost(),
res -> res
));
}
}
The service layer takes the responsability of calling both PostRepository#fetchPosts(...) and then PostVoteRepository#findByUser(...), then mixes the results in a DTO to send to the presentation layer above.
This is the solution I'm currently using. However, I don't feel like having a ~50 parameters long in clause might be a good idea. Also, having a separate Repository class for PostVote may be a bit overkill and break the purpose of ORMs.
3° solution
I haven't tested it so it might have an incorrect syntax, but the idea is to wrap the Post and PostVote entity in a VotedPost DTO.
public class VotedPost{
private Post post;
private PostVote postVote;
public VotedPost(Post post, PostVote postVote){
this.post = post;
this.postVote = postVote;
}
//getters
}
I obtain the object with a query like this:
select new my.pkg.VotedPost(p, pv) from Post p
left join fetch PostVote pv on p = pv.post and pv.user = :user
This gives me more type safeness than the the solutions based on Object[] or Tuple query results. Looks like a better alternative than the solution 2 but adopting the solution 1 in a efficient way would be the best.
What is, generally, the best approach in problems like this? I'm using Hibernate as JPA implementation.
I could imagine the standard bi-directional association using #OneToMany being a maintainable yet performant solution.
To mitigate n+1 selects, one could use e.g.:
#EntityGraph, to specify which associated data is to be loaded (e.g. one user with all of it's posts and all associated votes within one single select query)
Hibernates #BatchSize, e.g. to load votes for multiple posts at once when iterating over all posts of a user, instead having one query for each collection of votes of each post
When it comes to restricting users to perform accesses in less performant ways, I'd argue that it should be up the API to document possible performance impacts and offer performant alternatives for different use-cases.
(As a user of an API one might always find ways to implement things in the least performant fashion:)
I need some help with the JPA Framework.
I've read some answers "kind of" about this topic but I couldn't reach any conclusion.
First heres an examplo of the design i'm wooking with.
#BusinessObject
public class ClassA {
#Column(name = "ID", nullable = false)
private Long id;
#OneToMany(mappedBy = "classAAttr")
private Collection<ClassAB> classABCollection;
//STUFF AND OTHER COLUMNS.....
}
public class ClassAB {
#Column(name = "ID", nullable = false)
private Long id;
#JoinColumn(name = "TABLE_A_ID", referencedColumnName = "ID")
#ManyToOne
private ClassA classAAttr;
#JoinColumn(name = "TABLE_B_ID", referencedColumnName = "ID")
#ManyToOne
private ClassB classBAttr;
//STUFF AND OTHER COLUMNS.....
}
#BusinessObject
public class ClassB {
#Column(name = "ID", nullable = false)
private Long id;
#Column(name = "ORDERCLAUSE", nullable = false)
private String orderClause;
//STUFF AND OTHER COLUMNS.....
}
So I need to order the classABCollection in ClassA by the orderClause attribute in ClassB, but I can't find the right #OrderBy() clause AND/OR location for it.
I've read some things about the Comparator Interface but, unfortunately, due to business policy, I need to be sure that there is no other way...
How Should I Do It?
Thank you guys in advance.
The API docs for #OrderBy note:
The property or field name must correspond to that of a persistent
property or field of the associated class or embedded class within :
http://docs.oracle.com/javaee/6/api/javax/persistence/OrderBy.html
so sorting AB in A by a property of B is not possible.
The alternatives are to write a query or do an in memory sort by some means. Hibernate, for example, has an #Sort annotation which you can use to apply an in-memory sort on load, either by having the target Entity implement Comparable or by specifying a Comparator:
See section 2.4.6.1:
http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/
So - I found a roundabout. A query like one below wont work:
select * from A a where xyz
order by a.reference or a.reference.id
However, I found that by adding a function, we can make the query work:
(Do note, the reference need not be null.. and use appropriate values.)
select * from A a where xyz
order by coalesce(a.reference , 0)
I've got a question about Spring JPA (JPQL and sorts).
Been searching my ass of for this and i can't seem to find an answer.
If there is any duplicate, please let me know. I haven't come across a question/tutorial/guide that fits my needs.
Okay so i got Spring with JPA. And i have 2 entities.
Asset and AssetStatus. An Asset could have multiple AssetStatuses, one AssetStatus belongs to an Asset.
The entities are build as following. I omitted the unneeded properties.
Asset:
#Entity
#Table(name = "T_ASSET")
public class Asset implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#OneToMany(mappedBy = "asset", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private List<AssetStatus> assetStatus;
}
AssetStatus:
#Entity
#Table(name = "T_ASSETSTATUS")
public class AssetStatus implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotNull
#Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
#JsonSerialize(using = CustomLocalDateTimeSerializer.class)
#JsonDeserialize(using = CustomLocalDateTimeDeserializer.class)
#Column(name = "timestamp", nullable = false, insertable = true, updatable = true)
private LocalDateTime timestamp;
#JsonIgnore
#NotNull
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Asset asset;
}
And i got a standard AssetRepository. (Ignore the find by barcode, its an omitted property from Asset.)
public interface AssetRepository extends JpaRepository<Asset, Long>, QueryDslPredicateExecutor<Asset> {
Asset findOneByBarcode(String barcode);
}
Now i want to get all my assets, with the last AssetStatus they had. Which is defined by the timestamp in AssetStatus. Getting all assets works but i also get all AssetStatuses they have (or had). I just want the most recent.
How do i manage to do this? I tried writing a custom query with #Query. Or name a method like findLastAssetStatus() or something. All didn't work.
Is there someone who could help me figure this out? I am willing to give more information and answer any questions asked.
EDIT: I found out the query in MySQL to get the wanted result (Works in MySQL Workbench on my database):
SELECT * FROM T_ASSET asset JOIN T_ASSETSTATUS assetStatus WHERE asset.id = assetStatus.asset_id AND assetStatus.timestamp = (SELECT max(timestamp) FROM T_ASSETSTATUS WHERE asset_id = asset.id);
As i use this in my AssetRepository with #query nativequery=true (As specified below), it does not give me the wanted result. This will still give me every status with every assetStatus it has ever had.
#Query(value = "SELECT * FROM T_ASSET asset JOIN T_ASSETSTATUS assetStatus WHERE asset.id = assetStatus.asset_id AND assetStatus.timestamp = (SELECT max(timestamp) FROM T_ASSETSTATUS WHERE asset_id = asset.id)", nativeQuery = true)
List<Asset> findAssetWithlastStatus();
How do i write this query in JPQL? Or solve this in any other way?
Thanks in advance!
Cheers, Clemenz
You can take a look at Hibernate filters. Write a filter which will filter out the old statuses and enable it in the sessions in which you want it to be applied.
I need some help with the JPA Framework.
I've read some answers "kind of" about this topic but I couldn't reach any conclusion.
First heres an examplo of the design i'm wooking with.
#BusinessObject
public class ClassA {
#Column(name = "ID", nullable = false)
private Long id;
#OneToMany(mappedBy = "classAAttr")
private Collection<ClassAB> classABCollection;
//STUFF AND OTHER COLUMNS.....
}
public class ClassAB {
#Column(name = "ID", nullable = false)
private Long id;
#JoinColumn(name = "TABLE_A_ID", referencedColumnName = "ID")
#ManyToOne
private ClassA classAAttr;
#JoinColumn(name = "TABLE_B_ID", referencedColumnName = "ID")
#ManyToOne
private ClassB classBAttr;
//STUFF AND OTHER COLUMNS.....
}
#BusinessObject
public class ClassB {
#Column(name = "ID", nullable = false)
private Long id;
#Column(name = "ORDERCLAUSE", nullable = false)
private String orderClause;
//STUFF AND OTHER COLUMNS.....
}
So I need to order the classABCollection in ClassA by the orderClause attribute in ClassB, but I can't find the right #OrderBy() clause AND/OR location for it.
I've read some things about the Comparator Interface but, unfortunately, due to business policy, I need to be sure that there is no other way...
How Should I Do It?
Thank you guys in advance.
The API docs for #OrderBy note:
The property or field name must correspond to that of a persistent
property or field of the associated class or embedded class within :
http://docs.oracle.com/javaee/6/api/javax/persistence/OrderBy.html
so sorting AB in A by a property of B is not possible.
The alternatives are to write a query or do an in memory sort by some means. Hibernate, for example, has an #Sort annotation which you can use to apply an in-memory sort on load, either by having the target Entity implement Comparable or by specifying a Comparator:
See section 2.4.6.1:
http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/
So - I found a roundabout. A query like one below wont work:
select * from A a where xyz
order by a.reference or a.reference.id
However, I found that by adding a function, we can make the query work:
(Do note, the reference need not be null.. and use appropriate values.)
select * from A a where xyz
order by coalesce(a.reference , 0)
Imagine, an Event entity references a Status Entity:
#Entity
#Table(name = "event")
public class Event()
{
#Id
#Column(name = "id", nullable = false)
private long id;
...
#ManyToOne
#JoinColumn(name = "status_code", nullable = false)
private Status status;
}
#Entity
#Table(name = "status")
public class Status()
{
#Id
#Column(name = "code", nullable = false)
private String code;
#Column(name = "label", nullable = false, updatable = false)
private String label;
}
Status is mapped to a small table 'status'. Status is a typical reference data / lookup Entity.
code label
----- --------------
CRD Created
ITD Initiated
PSD Paused
CCD Cancelled
ABD Aborted
I'm not sure if it is a good idea to model Status as an Entity. It feels more like an enumeration of constants...
By mapping Status as an Entity, I can use Status objects in Java code, and the Status values are equally present in the database. This is good for reporting.
On the other hand, if I want to set a particular Status to an Event, I can't simply assign the constant status I have in mind. I have to lookup the right entity first:
event.setStatus(entityManager.find(Status.class, "CRD"))
Can I avoid the above code fragment? I'm affraid for a performance penalty and it looks very heavy...
Do I have to tweak things with read-only attributes?
Can I prefetch these lookup entities and use them as constants?
Did I miss a crucial JPA feature?
...?
All opinions / suggestions / recommendations are welcome!
Thank you!
J.
You could use entityManager.getReference(Status.class, "CRD"), which might not fetch the entity from the database if it is only used to set a foreign key.
Can I avoid the above code fragment? I'm affraid for a performance penalty and it looks very heavy?
Well, you could use an enum instead. I don't really see why you don't actually.
But if you really want to use an entity, then it would be a perfect candidate for 2nd level caching and this would solve your performance concern.