0

I use hibernate and SQL requests for accessing to entities in DB. I don't use eager/lazy loading, because prefer using SQL requests than ORM. Sometimes I need to get child entities for main entity, so I do next:

List<ChildEntity> tempList = (List<ChildEntity>) getSession()
    .createSQLQuery(SQL_QUERY)
    .addScalar(...)
    ...
    .list();

And then doing next:

Set<ChildEntity> childEntities = new LinkedHashSet<ChildEntity>();

And add all elements from list to set using iterator. Then I set this childEntities to main entity. Is that normal way in hibernate?

And also why all recommend to use Set instead of List in One To Many relationship, but hibernate method for getting list of entities .list() return List, not Set?

Dark Hydra
  • 265
  • 6
  • 21

1 Answers1

0

Take a look at this post @OneToMany List<> vs Set<> difference

Using a Set or a SortedSet .. instead of list will also guarantee the integrity of your data.

Sometimes you have to override equals and hascode so the parent entity will only accept a correct child entity, for example if you have a Child entity Student and that a parent entity College, every student has an admission number that has to be unique..

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

import com.google.common.base.Objects;

@Entity
public class Student implements Comparable<Student> {

    @Id
    @GeneratedValue
    private Long idCollege;

    @Basic
    @Column(name = "AD_NUM", unique = true)
    private String adminssionNumber;

    @ManyToOne
    @JoinColumn(name = "COL_ID")
    private College college;

    @Override
    public int compareTo(Student o) {
        return adminssionNumber.compareTo(o.adminssionNumber);
    }

    @Override
    public boolean equals(Object obj) {
        return obj == this || (obj instanceof Student && equals((Student) obj));
    }

    private final boolean equals(Student other) {
        return other != null && equal(adminssionNumber, other.adminssionNumber);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(adminssionNumber, getClass());
    }
}

College

import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class College {

    @Id
    @GeneratedValue
    private Long idCollege;

    @OneToMany(mappedBy = "college")
    private Set<Student> students;

    @Column(name = "NAME")
    private String name;
//other properties
}
Community
  • 1
  • 1
Rafik BELDI
  • 4,140
  • 4
  • 24
  • 38