简体   繁体   中英

how to select specific column which is an object in jpa spring boot

well I have a doubt, i have a class like this:

@Entity(name = "movie_details")
@Getter @Setter
public class MovieDetailEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private long id;

    @ManyToOne
    @JoinColumn(name = "movie_id", nullable = false)
    @JsonIgnoreProperties(value = {"movieDetails", "handler","hibernateLazyInitializer"}, allowSetters = true)
    private MovieEntity movie;

    @ManyToOne
    @JoinColumn(name = "character_id", nullable = false)
    @JsonIgnoreProperties(value = {"movies", "handler","hibernateLazyInitializer"}, allowSetters = true)
    private CharacterEntity character;
}

And I just want to show the characters from a movie, but I don't want to show the id and the MovieEntity I just want to show CharacterEntity...

@Repository
public interface MovieDetailRepository extends JpaRepository<MovieDetailEntity, Long> {
    Page<MovieDetailEntity> findByMovie(Pageable pageable, MovieEntity movie);
}

And this query return a json like this

"content": [
        {
            "id": ...,
            "movie": {
                ...
            },
            "character": {
                ...
            }
        }
    ],

I was reading about making an interface dto with getters but didn't work for me

It sounds like you want to turn your entity into a DTO object that you can return. You'd need to create a new object like

public class MovieDetailDto {
    private CharacterDto;
}

You would then probably want to implement a setter and getter method for CharacterDto and create the CharacterDto class similarly to the MovieDetailDto class with the fields from CharacterEntity you want to return with setters and getters for them.

When you get back a MovieDetailEntity from your repository you can then just create a new CharacterDto for the CharacterEntity and set it in a new MovieDetailDto.

I have could solve it, i create a interface projection, like this...

public interface MovieCharactersDto {
    CharacterEntity getCharacter();
    interface CharacterEntity {
        Long getId();
        String getName();
        String getImage();
        BigDecimal getWeight();
        Integer getAge();
        String getStory();
    }
}

And the query was as follows:

@Repository
public interface MovieDetailRepository extends JpaRepository<MovieDetailEntity, Long> {
    Page<MovieCharactersDto> findByMovie(Pageable pageable, MovieEntity movie);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM