Search code examples
javaspringspring-boothibernatejpa

I want children objects but I want to search them by parent fields in Hibernate


How I can get all children objects by filtering them by a nickname of their parents?

I have parent entity:

import jakarta.persistence.*;
import lombok.Data;
import org.hibernate.validator.constraints.Length;

@Entity
@Data
@Table(name = "parent")
public class ParentEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Byte id;

    private Integer age;
    
    @Column(columnDefinition = "VARCHAR(100)")
    private String nickname;
}

I have child entity:

import jakarta.persistence.*;
import lombok.Data;
import org.hibernate.validator.constraints.Length;

@Entity
@Data
@Table(name = "child")
public class ChildEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    private String surname;

    @Column(name = "parent_id", nullable = false)
    private Byte parentId;

    @ManyToOne(targetEntity = ParentEntity.class)
    @JoinColumn(name = "parent_id", updatable = false, insertable = false)
    private ParentEntity parentEntity;
}

And I have a repository:

import com.example.ParentEntity;
import com.example.ChildEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface ChildRepository extends JpaRepository<ChildEntity, String> {
    // I guess something like this but I was not able to figure out
    List<ChildEntity> findAllByParentEntity(String nickname);
}

Solution

  • This will return all the ChildEntity whose parent has the nickname in parameter :

    @Query("SELECT c FROM ChildEntity c join c.parentEntity p WHERE p.nickname = :nickname")
    List<ChildEntity> retrieveByParentNickName(@Param("nickname") String nickname);