Question

i have one doubt, that is when we create one-to-many as bidirectional. we will put one parent class reference in child class.

see the code.

Person.java

@Entity
@Table(name="PERSON")
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="personId")
     private int id;
    @Column(name="personName")
    private String name;
    @OneToMany(cascade =CascadeType.ALL,fetch = FetchType.LAZY)
    @JoinColumn(name="personId") 
    private Set <Address> addresses;
         ....
         ....
}

Address.java

@Entity
@Table(name = "ADDRESS")
public class Address {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "addressId")
    private int id;
    @Column(name = "address",nullable=false)
    private String address;
    @ManyToOne(cascade =CascadeType.ALL)
    @JoinColumn(name="personId",nullable=false)
    private Person person;
           ....
           ....
    }

here Person.java is parent class and Address.java is child class. when we fetch the parent object from data base it is loading child class. it is fine. no proble.

but in vice versa ie. if we are fetching child class it is also holding parent class (person).

eg: we fetch Address by address id. just assume retrieved 100 address from data base.

but in address class person variable hold the parent(Person) object aslo.

my doubt is here

is use different 100 memory of person. with same data. in Address class. ?

my dao is like this.

public List<Address> getAllAddressByPersonId(int personId) {
        List<Address> addressList =  null;
        try {
            DetachedCriteria criteria = DetachedCriteria.forClass(Address.class);
            criteria.createCriteria("person").add(Restrictions.eq("id", personId));
            addressList = getHibernateTemplate().findByCriteria(criteria);
        } catch (HibernateException e) {
            e.printStackTrace();
        } catch (DataAccessException e) {
            e.printStackTrace();
        }

        return addressList;

just assume the size of addrssList is 100.

like

per =  addressList.get(0).getPerson() , 

per 1 = addressList.get(1).getPerson(),

per2 = addressList.get(2).getPerson(),

....

per99 =  addressList.get(99).getPerson(). 

here per1, per2 .... and per 99 are using same memory or different.

if same it is ok.. else it may cause of any performing issue of more memory utilization.?

help pls...

Was it helpful?

Solution

Hibernate does identity check. One hibernate session contains only single instance of an object with the same ID. So, if per, per1,...per99 is one person, you will have one object for it. Otherwise - different objects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top