Announcement Announcement Module
Collapse
No announcement yet.
Specifications - getting @OneToMany entity Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Specifications - getting @OneToMany entity

    Hi,

    I have a problem with getting List<Note> from entity Person using Spring data JPA specifications (because of pagination). I need to get all notes by person but dependency between these two entities is on Person side. I don't know how to create my Predicate because Note doesn't contain any attribute related to Person.

    I simply can get List<Note> with Persons getter but i can't use this way because i need returned data paginated. I am using findAll(Specifications,Pageable).


    Code:
        @Entity
        public class Person implements Serializable {
        
        	@Id
        	private Long personId;
        
        	@OneToMany
        	@JoinColumn(name = "personId")
        	private List<Note> notes;
        
        }
    
        @Entity
        public class Note implements Serializable {
        
        	@Id
        	private Long noteId;
        }
    I'm sure that Specifications are able to create query what I want, but I don't know how.Normally, I would write something like this, but i don't have an attribute person in Note and database can't be remapped at this stage.


    Code:
        public static Specification<Note> notesByPerson(final Long personId) {
        		return new Specification<Note>() {
        			@Override
        			public Predicate toPredicate(final Root<Note> root, final CriteriaQuery<?> query,
        					final CriteriaBuilder builder) {
        
        				final Path<Person> per = root.<Person> get("person");
        
        				return builder.equal(per.<Long> get("personId"), personId);
        
        			}
        		};
        	}
    Thank you,
    Zdend

  • #2
    Solved..
    Code:
    	public static Specification<Note> notesByPerson(final Long personId) {
    		return new Specification<Note>() {
    
    			@Override
    			public Predicate toPredicate(final Root<Note> noteRoot, final CriteriaQuery<?> query,
    					final CriteriaBuilder cb) {
    
    				final Subquery<Long> personQuery = query.subquery(Long.class);
    				final Root<Person> person = personQuery.from(Person.class);
    				final Join<Person, Note> notes = person.join("notes");
    				personQuery.select(notes.<Long> get("noteId"));
    				personQuery.where(cb.equal(person.<Long> get("personId"), personId));
    
    				return cb.in(noteRoot.get("noteId")).value(personQuery);
    			}
    		};
    	}

    Comment

    Working...
    X