Hibernate: Limit result size of child objects - java

I've got a parent entity which has many child objects, most of which are collections. See below.
#Entity
#Table(name = "A")
public class A {
#Id
#Column(name = "ID")
private long id;
#OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
#JoinColumn(name = "A_ID", nullable = false)
private Set<B> setB;
#OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
#JoinColumn(name = "A_ID", nullable = false)
private Set<C> setC;
#OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
#JoinColumn(name = "A_ID", nullable = false)
private Set<D> setD;
// Skipping more collections as they are not needed for the example
// Standard getters and setters
}
Now classes B, C and D have A_ID and 5 more String columns. Please consider them B1,B2,B3,B4,B5 and so on.
I also have a CrudRepository for A
#Repository
public interface ARepository extends CrudRepository<A, Long> {
Optional<A> findById(Long id);
}
I want to fetch the complete A object with an id but the other child collections that A have (setB, setC, setD) contains approx thousands of rows for each A_ID. I want to put a filter to fetch only first 100 rows for a given A_ID.
I have tried putting #Where(clause = "ROWNUM < 101") on the collections but it does not work as in the query the table name gets prefixed to the ROWNUM.
I also took a look at Criteria and Criterion but I am unable to find any working solution.
Since there are many collection of Objects in the parent class. So using native queries for each object would be too much rework.
Can anyone please help me with this. Do comment if you need more information.
Thanks

That's not so easy. You would have to fetch the collections manually or use a library like Blaze-Persistence Entity-Views on top that supports this out of the box. Also see here for a similar question: Hibernate - Limit size of nested collection
In your particular case, this could look like the following:
#EntityView(A.class)
public interface ADto {
#IdMapping
long getId();
#Limit(limit = "100", order = "id asc")
Set<BDto> getSetB();
#Limit(limit = "100", order = "id asc")
Set<C> getSetC();
#Limit(limit = "100", order = "id asc")
Set<D> getSetD();
}

Related

How do I select information from ManyToMany Table in JPA?

I have two entities mapped Board and Tag by #ManyToMany to a join table board_tag_table.
How would I return the top 5 most common tag_id in the board_tag_table?
enter image description here
public class Board {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
#JoinTable(name = "board_tag_table",
joinColumns = {
//primary key of Board
#JoinColumn(name = "id", referencedColumnName = "id")
},
inverseJoinColumns = {
//primary key of Tag
#JoinColumn(name = "tag_id", referencedColumnName = "tag_id")
})
private Set<Tag> tags = new HashSet<>();
}
public class Tag {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer tag_id;
private String tagname;
#JsonIgnore
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "tags")
private Set<Board> boards = new HashSet<>();
}
Unable to find how to query within a many to many table
you can pass through foreach and write your query in Tag repository, but I think you can't write query, because they are have list from two sides
Consider using a native query instead.
If you want to use the JPA, you can add a field (Eg. usedCount) in the Tag entity and follow the instructions here https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.limit-query-result.
The query should look like this:
List<Tag> findByUsedCount(Sort sort, Pageable pageable);
Don't look at it as trying to access the board_tag_table, and instead look at how you would do this with the java entities themselves. This would be just selecting the 5 top Tags based on the number of boards they have. "select t.tag_id, count(b) as boardCount from Tag t join t.boards b group by t.tag_id order by boardCount", then use maxResults to limit the returned values to 5

QueryDsl invert manyToMany join

Given we have the following entities that form a many-to-many relationship:
#Entity
public class A {
#Id
private Long id;
private String name;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(
name = "A_B",
joinColumns = #JoinColumn(name = "id_a"),
inverseJoinColumns = #JoinColumn(name = "id_b"))
private Set<B> listing;
}
#Entity
public class B {
#Id
private Long id;
}
I need to write a query that fetches B and applies some WHERE criteria on A side.
Since the relationsip is modeled from A entity's side it's very easy to write a query that joins these itsself:
new JPAQuery<>(entityManager)
.select(QB.b)
.from(QA.a)
.join(QA.a.listing,b)
.where(QA.a.name.eq("test"))
.fetch();
However since A_B table can be duplicated, this query can produce duplicate entries, which does not do for my scenario. So instead I need to start FROM B and JOIN A. And this is where I need help. I tried:
new JPAQuery<>(entityManager)
.select(QB.b)
.from(QB.b)
.join(QA.a).on(QA.a.listing.any().eq(QB.b))
.where(QA.a.name.eq("test"))
.fetch();
But that does not work as any() merely produces a subselect, instead of many to many join.
How do I write this query in Querydsl?

Hibernate ManyToMany wtih column child removal

I have Many To Many with additional column. Here realization(getters/setters generated by lombok, removed for clarity):
public class User extends BaseEntity {
#OneToMany(mappedBy = "user",
orphanRemoval = true,
fetch = FetchType.LAZY
cascade = CascadeType.ALL,)
private List<UserEvent> attendeeEvents = new ArrayList<>();
}
#Table(
name = "UC_USER_EVENT",
uniqueConstraints = {#UniqueConstraint(columnNames = {"user_id", "event_id"})}
)
public class UserEvent extends BaseEntity {
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "event_id")
private Event event;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "user_id")
private User user;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "user_response_id")
private UserResponse userResponse;
}
public class Event extends BaseEntity {
#OneToMany(mappedBy = "event",
orphanRemoval = true,
fetch = FetchType.EAGER,
cascade = CascadeType.ALL)
private List<UserEvent> userEvents = new ArrayList<>();
}
I want this - when i delete Event, All "UserEvents" connected to it should be removed. And if I delete User, all "UserEvents" should be removed too.
I delete my event(eventRepository is Spring Jpa interface):
eventRepository.delete(event);
Then retrieving UserEvents from db:
List<UserEvent> userEvents = userEventsId.stream()
.map(id -> entityManager.find(UserEvent.class, id)).collect(Collectors.toList());
And there is collection with 2 items(this is count of UserEvents), but they all "null".
I can't understand what happening and how to do it right.
I need them deleted and when I check collection there should be 0, instead of 2.
The delete says marked for deletion, please try calling flush after deletion, and then find.
I guess find goes to the database, find the two rows, but when trying to instantiate them, find the entities marked for deletion and then you have this strange behaviour.
Recomendation: try to abstract more from the database and use less annotations. Learn the conventions of names for columns and tables (if you need to) and let JPA do its job.

Cascade persist creates duplicate rows?

I'm creating a database entity object Order, and assign it to multiple entities of type BookingCode.
Problem: this creates a single order in db, which is fine. But the order itself has a #OneToOne OrderDescription, which occurs duplicate in the database.
#Entity
public class BookingCode {
#Id
private Long id;
#ManyToOne(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.DETACH})
private Order order;
}
#Entity
public class Order {
#Id
private Long id;
private String orderName;
#OneToOne(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
private OrderDescription description;
}
#Entity
public class OrderDescription {
#Id
private Long id;
//for simplicity just one text element; of course multiple fields in real life
private String text;
#OneToOne
private Order order;
}
Test:
Order order = new Order();
order.setOrderName("test");
OrderDescription d = new OrderDescription("testdescr");
d.setOrder(order);
order.setDescription(d);
List<BookingCodes> codes = new ArrayList<>();
BookingCode code = new BookingCode();
code.setOrder(order);
codes.add(order);
BookingCode code2 = new BookingCode();
code2.setOrder(order); //using the same offer entity!
codes.add(order2);
codes = dao.save(codes); //CrudRepository from Spring
dao.findOne(codes.get(0).getId()); //this works, find an order which has one of the OrderDescriptions
Result:
In my database I then have two OrderDescription entries, where I would expect only one, because I reused the same Order object and assigned it to different BookingCode objects.
Like:
table order_descrption:
1;"de";"testdescr";"123456"
2;"de";"testdescr";"123456"
As Order has a #OneToOne relation to OrderDescription
And I even don't understand why the select using findOne() works correctly. Because in database I now have two OrderDescriptions that map to the same Order, but an Order can only have one of them.
Persist the order first and then assign it to both bookingCode .
I had a similar issue where I had an Order obj and its variable prevOrder was referring to itself i.e. Order entity. And when I stored order, it would end up storing duplicate records for prevOrder.
I had the following code:
#Entity
#Table(name = "orders")
public class Order implements Serializable {
#Id
#GeneratedValue(generator = "order_id_generator")
#SequenceGenerator(name = "order_id_generator", sequenceName = "order_id_sequence", allocationSize = 1)
#Column(name = "id", updatable = false, nullable = false)
private Long id;
#OneToOne(cascade = CascadeType.ALL, optional = true)
#JoinColumn(name = "previous_order_id", unique = true, updatable = false, referencedColumnName = "id")
private Order previousOrder;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "previousOrder")
private Order nextOrder;
...
I tried various things including overriding equals and hashcode of Order, and adding a OneToOne mappedBy field 'nextOrder' etc. But noticed JPA didn't even call equals() to determine object's uniqueness. Ultimately I found out that JPA uses id field as the object's identifier and I wasn't storing the generated id while storing the object to a distrobuted cache. So it was all the time creating fresh objects during persistence.

Hibernate criteria many to many

I have two entities with many to many relationship:
#Entity
#Table(name = "items")
public class Item implements Comparable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "item_id")
private Integer itemId;
#ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
#JoinTable(name = "items_criteria",
joinColumns = #JoinColumn(name = "item_id"),
inverseJoinColumns = #JoinColumn(name = "filter_criterion_id"))
private List<FilterCriterion> filterCriteria;
}
and
#Entity
#Table(name = "filter_criteria")
public class FilterCriterion {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "filter_criterion_id")
private Integer filterCriterionId;
#ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
#JoinTable(name = "items_criteria",
joinColumns = #JoinColumn(name = "filter_criterion_id"),
inverseJoinColumns = #JoinColumn(name = "item_id"))
private List<Item> items;
}
I need to write function in ItemDao class that returns List of Items which have all elements of the collection given as an argument. In the example below I use Restrictions.in so the result contains even those Items which contain for example only one FilterCriterion from List given as argument. I need to have in the result only those Items, which contain all of the elements in argument List.
public List<Item> getItems(List<FilterCriterion> currentFilterCriteria) {
Criteria criteria = ht.getSessionFactory().getCurrentSession().createCriteria(Item.class);
List<Integer>currentFilterCriteriaId = new ArrayList<Integer>();
for(FilterCriterion criterion : currentFilterCriteria){
currentFilterCriteriaId.add(criterion.getFilterCriterionId());
}
if(!currentFilterCriteriaId.isEmpty()){
criteria.createAlias("filterCriteria", "f");
criteria.add(Restrictions.in("f.filterCriterionId", currentFilterCriteriaId));
}
return criteria.list();
}
First of all, you'll have to fix your mapping. You don't have a bidirectional ManyToMany association here, but two, unrelated, unidirectional ManyToMany associations. One side must be the inverse side by using the mappedBy attribute:
#ManyToMany(mappedBy = "filterCriteria")
private List<Item> items;
Now to your question, one way of doing this is to use such a query. I'll let you translate it to Criteria if you really want to. I'd use HQL instead, since it's so much easier and maintainable:
select i from Item i
where :criteriaIdSetSize = (select count(c.id) from Item i2
inner join i2.filterCriteria c
where c.id in :criteriaIdSet
and i2 = i)
You should use a Set to hold your criteria IDs rather than a list though, to make sure it doesn't contain duplicates (which would make the result incorrect).

Categories