Home > database >  I'd like to get data from different table using @JoinColumns - how to make a condition in which
I'd like to get data from different table using @JoinColumns - how to make a condition in which

Time:10-26

Let's assume I have code like this:

Entity
public class Order {
    private Integer exampleNumber;

    // ...
}

@Entity
public class User {  
   private List<Order> orders;
   private Integer exampleNumber;

   @OneToMany(fetch = FetchType.LAZY)
   @JoinColumns({@JoinColumn(name = "user_nr", referencedColumnName = "id")})
   public List<Order> getOrders() {
       return this.orders;
   }

   public Integer getExampleNumber() {
        return this.exampleNumber;
   };

   // ...
}

I'd like to get only those orders in my method getOrders() that User.getExampleNumber() = Order.getExampleNumber. How can I add the condition to this method getOrders() in the easiest way? Is possible to pass the argument in @Filter, @WhereJoinTable or do I need to use something else?

CodePudding user response:

This is not possible in JPA to pass values

But you can use

@Where

like

@Where(clause="example_nr=...")

else, suggested method is to use Hibernate criteria.

Criteria criteria = session.createCriteria(User.class);
...

CodePudding user response:

In the User model place this code

    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="post")
    private List<Order> orders;

In the Order table palce this code

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "user_id", nullable = false)
    @JsonIgnore
    private User user;

With this you can able to fetch all orders related to user when you are fetching the User details

  • Related