Miha Jamsek
Miha Jamsek

Reputation: 1273

Spring Boot JPA populate entity field with query

I am building a menu in my application, so I have made entity MenuItem, which represents one item in my menu. This can be either a file or directory.

However, I want to know whether a directory has any children or not, because if it doesn't I do not want to display it. I also do not want to have this number of children hardcoded, because that would mean I would have to update the value everytime I add something.

What I want to know is, if there is a way to map an attribute with a query instead of a persisted value.

This is my MenuItem.java file:

@Entity
@Table(name = "menu_item")
public class MenuItem {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column
    private long parent;

    @Column
    private String name;

    @Column
    private long num_of_childs;

    @Enumerated(EnumType.STRING)
    @Column
    private MenuItemType type;

    @ManyToOne
    @JoinColumn(name = "file_id")
    private FileItem file;

    /* getters and setters... */
}

What I want is something like this:

@Column
@Transient
@Query("SELECT COUNT(i) as num_of_childs FROM MenuItem i WHERE parent = i.id")
private long num_of_childs;

Is it even possible to do such thing?

Upvotes: 7

Views: 8424

Answers (3)

Mehtrick
Mehtrick

Reputation: 526

You can create a count Method in your Repository

 @Repository
 interface MenuItemRepository extends JpaRepository<MenuItem, Long> {

    long countByParent(String lastname);
 }

Upvotes: -1

Michael Seiler
Michael Seiler

Reputation: 650

You can create a Repository for that Entity and use JPA to count all occurances

@Repository
public interface MenuItemRepository extends JpaRepository<MenuItem, Long> {

    public int countByParent(long parent);

} 

Than just use the JPA-Method

Upvotes: 0

Boyen
Boyen

Reputation: 1549

Hibernate allows you to do this with @Formula.

Example :

@Formula("SELECT COUNT(i) FROM MenuItem i WHERE parent = i.id")
private long num_of_childs;

However, in your case it might be best to keep a list of child menu items, as you will need that in your application anyway.

Upvotes: 4

Related Questions