1

am new to Hibernate. I have two tables named "User" and "Details". These two tables are mapped as " one-to-many ". The mapping process is given as follow.

    @Entity
    public class User { 
    private int id;
    private Strng name;

    @OneToMany(mappedBy ="user" )

    private Collection<Details> details;//= new ArrayList<Details>();
    ....getters and setters.....
   }

and Details class is

    @Entity
    public class Details{ 
    private int id;
    private Strng address;
    private String deleted;
    }

And this one to many relation works fine..

Now i want to retrieve the data from " details " table of particular record in " user " table with an additional condition ie, "deleted " field is equal to the string "NO".

For this requirement hibernate, how can i achieve this one.

Filters or criteria or some one else ,, which one is the best way to solve my problem, with out break the relation.

I mean , with the help of relations we simple get all the data at single line of code, like " user_obj.getDetails()" . In the same way we can simple get the data from the data base with extra conditions with less code.

Thank u to all,, in advance.......

Ramesh J
  • 794
  • 2
  • 11
  • 24
  • yep, you can annotate your class using NamedQueries and NamedQuery, where you can write the query yourself, and then just execute it from where you need it - http://web.securityinnovation.com/appsec-weekly/blog/bid/69738/Use-Named-Queries-with-Hibernate – Jan Hruby Jun 03 '13 at 10:36

1 Answers1

1

You can achieve it using Hibernate filters

First define a filter on your child table i,e Details

@Entity
@FilterDef(name="filterDeleted", defaultCondition="Deleted='NO'")
public class Details{ 

then you need to have @Filter annotation on parent table i,e User

    @Entity
    public class User { 
    private int id;
    private Strng name;

    @OneToMany(mappedBy ="user" )
    @Filter(name="filterDeleted")
    private Collection<Details> details;//= new ArrayList<Details>();
    ....getters and setters.....
   }

and you need to enable the filter while fetching the content

session.enableFilter("filterDeleted");
session.load(...);

Please see this thread for more reference

But I would suggest you to avoid filters if the data is too large, cause I have experienced trouble using @OnetoMany with @Filter and later i had to fetch the child table separately using Criteria and attach them.

Community
  • 1
  • 1
sanbhat
  • 17,522
  • 6
  • 48
  • 64