7

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?

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

-1

You can create a count Method in your Repository

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

    long countByParent(String lastname);
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.