Hibernate запрос из базы данных с помощью Criteria

169
22 декабря 2017, 01:17

Есть 3 таблицы в базе данных MySql. Вот их классы.

Класс родитель. Раздает id

   @MappedSuperclass
public class HotelEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
public HotelEntity(Integer id){
    this.id=id;
}
public  HotelEntity(){}
    @Id
    @Column(name = "id")
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
}

Класс Гость

@Entity
@Table(name = "guest")
public class Guest extends HotelEntity{
    private String name;
    private String surname;
    @JsonCreator
    public Guest(Integer id,  String name,  String surName) {
        super(id);
        this.name = name;
        this.surname = surName;
    }
public Guest(){}
    @Basic
    @Column(name = "name")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Basic
    @Column(name = "surname")
    public String getSurname() {
        return surname;
    }
    public void setSurname(String surname) {
        this.surname = surname;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Guest that = (Guest) o;
        if (getId() != that.getId()) return false;
        if (name != null ? !name.equals(that.name) : that.name != null) return false;
        if (surname != null ? !surname.equals(that.surname) : that.surname != null) return false;
        return true;
    }
    @Override
    public int hashCode() {
        int result = getId();
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (surname != null ? surname.hashCode() : 0);
        return result;
    }
}

Класс услуга

    @Entity
@Table(name = "service")
public class Service extends HotelEntity{
    private String name;
    private Integer cost;
    private ServiceType type;
    public Service(Integer id, ServiceType type, String name, int cost) {
        super(id);
        this.name = name;
        this.cost = cost;
        this.type = type;
    }
    public Service(){
    }
    @Basic
    @Column(name = "name")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Basic
    @Column(name = "cost")
    public Integer getCost() {
        return cost;
    }
    public void setCost(Integer cost) {
        this.cost = cost;
    }
    @Basic
    @Column(name = "type")
    public ServiceType getType() {
        return type;
    }
    public void setType(ServiceType type) {
        this.type = type;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Service that = (Service) o;
        if (getId() != that.getId()) return false;
        if (name != null ? !name.equals(that.name) : that.name != null) return false;
        if (cost != null ? !cost.equals(that.cost) : that.cost != null) return false;
        if (type != null ? !type.equals(that.type) : that.type != null) return false;
        return true;
    }
    @Override
    public int hashCode() {
        int result = getId();
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (cost != null ? cost.hashCode() : 0);
        result = 31 * result + (type != null ? type.hashCode() : 0);
        return result;
    }
    @Override
    public String toString() {
        String str=this.getId()+this.name;
        return str;
    }
}

Класс с информацией о заказанной услуге и госте(id,date,guest_id,service_id)

    @Entity
@Table(name = "guestserviceinfo")
public class GuestServiceInfo extends HotelEntity{
    private Guest guest;
    private Service service;
    private Date date;
    public GuestServiceInfo(Integer id, Guest guest, Service service, Date date) {
        super(id);
        this.guest=guest;
        this.service=service;
        this.date=date;
    }
public GuestServiceInfo(){}
    @Basic
    @Column(name = "date")
    public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }
    @ManyToOne(cascade = CascadeType.ALL)
    public Guest getGuest() {
        return guest;
    }
    public void setGuest(Guest guest) {
        this.guest = guest;
    }
    @ManyToOne(cascade = CascadeType.ALL)
    public Service getService() {
        return service;
    }
    public void setService(Service service) {
        this.service = service;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        GuestServiceInfo that = (GuestServiceInfo) o;
        if (getId() != that.getId()) return false;
        if (date != null ? !date.equals(that.date) : that.date != null) return false;
        return true;
    }
    @Override
    public int hashCode() {
        int result =(int) getId();
        result = 31 * result + (date != null ? date.hashCode() : 0);
        return result;
    }
}

Мне нужно получить список услуг, у которых id гостя, допустим, равно 1. Sql использовать нельзя. Только criteria.В крайнем случае HQL. Как это делается?

Answer 1

Пишите такой метода, в который передаете сессию(как создать сессию - не предмет обусждения, поэтому считаем , что получаем ее в параметрах), а также экземпляр класса Guest, по айдишнику которого вы хотите искать.

public List <GuestServiceInfo > getGuestServiceInfoByGuest (Session session, Guest guest ){
    Query createQuery = session.createQuery("from GuestServiceInfo where guest = :guest"); 
                createQuery.setParameter("guest", guest); 
    List <GuestServiceInfo > guestServiceInfoList = query.list();
    return guestServiceInfoList;
    }

Но вообще -то, если вы юзаете хибернейт, то вы можете вытянуть данные по их связи, ведь в классе GuestServiceInfo есть связь ManyToOne и поле типа Guest , то вполне логично , что и у класса Guest должна быть связь OneToMany и коллекция типа GuestServiceInfo. Если обратиться к этой коллекции в пределах открытой сессии, то хибернейт по связи подтянет то, что вам надо без вских танцев с бубном. И именно этот способ является самым правильным и представляет собой соль ORM - модели.

Что касается критерии, то я не вижу смысла использовать ее в статических запросах. Слишком много кода для таких простых запросов приходится писать. Другое дело запрос динамический...

READ ALSO
Как восстановить BufferedImage после свернутого окна?

Как восстановить BufferedImage после свернутого окна?

Используя таймер рисую в BufferedImageВ этом же цикле таймера вывожу изображение на панель

181
Не могу обойти шаблон в поле ввода

Не могу обойти шаблон в поле ввода

ПриветствуюЕсть форма для заполнения анкеты

223
Как повесить события кнопок, чтобы при нажатии они имитровали e.keyCode цифр и клавише bakspace?

Как повесить события кнопок, чтобы при нажатии они имитровали e.keyCode цифр и клавише bakspace?

Как повесить события кнопок, чтобы при нажатии они имитровали ekeyCode цифр и клавише bakspace? В моем случае позиция курсора при нажатии по кнопкам...

184