Java Spring 查询

Java Spring Queries

我想查询 buy 我无权访问 h2 数据库架构,所以我不知道连接属性是如何命名的。 我基本上想在某个日期间隔内查询酒店的可用房间。为此,我需要进行如下查询:

   Select Room 
    From Room Inner Join Booking On Room.Id = Booking.RoomId Inner Join RoomType On RoomType.Id = Room.RoomTypeId
    Where NOT ((Booking.beginDate >= @initDate And Booking.beginDate <= @endtDate) or (Booking.beginDate >= @initDate And Booking.endDate <= @endDate)
or  (Booking.beginDate <= @initDate and Booking.endDate >= @endDate)) and Booking.Approved = 1 and RoomType.Id = @roomType)

在java spring:

@Query(........)
Iterable<Room> findAvaiableRooms(Date initDate, Date endDate, long roomType);

######## The Entities #######

@Entity
public class Booking {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;
    private Date beginDate;
    private Date endDate;
    private boolean aproved;

    @ManyToOne
    private Room room;
}



 @Entity
    public class Room {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private long id;
        private String name;

        @ManyToOne
        private RoomType roomType;

        @OneToMany(fetch = FetchType.LAZY, cascade=CascadeType.ALL, mappedBy="room", orphanRemoval = true)
        private Collection<Booking> bookings = new ArrayList<Booking>();
    }

@Entity
public class RoomType {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String type;
    private int price;
    private int numberOfRooms;

    @OneToMany(fetch = FetchType.LAZY, cascade=CascadeType.ALL, mappedBy="roomType", orphanRemoval = true)
    private Collection<Room> rooms = new ArrayList<Room>();
}

真不知道应该怎么查询才能和db保持一致。

您拥有所有这些 ORM 注释这一事实使我相信您正在使用 Hibernate。

我建议你忘掉 ORM,直到你能更自如地自己做。

您依赖 Hibernate 为您创建表,但没有完全理解它的作用。

您不知道如何编写 JOIN,所以您依赖于 Hibernate 为您生成的 SQL。

手动创建表格。编写一个使用您手工制作的 SQL 的数据访问 class。手动将这些结果映射到您的对象中。

完成后您就会真正理解问题所在。

您会欣赏(或鄙视)Hibernate 为您提供的功能,并了解它如何更好地工作。

您可以在注释中明确定义连接列的名称:

@Entity
public class Booking {

    @ManyToOne
    @JoinColumn(name="room_id")
    private Room room;
}

@Entity
public class Room {

    @ManyToOne
    @JoinColumn( name="roomType_id" )
    private RoomType roomType;

}

或者您也可以尝试使用 JPA 查询并使用对象关系而不是表

select Room r
from Room 
join r.bookings b
where 
not (   (b.beginDate >= :initDate And b.beginDate <= :endtDate)
    or  (b.beginDate >= :initDate And b.endDate   <= :endDate)
    or  (b.beginDate <= :initDate and b.endDate   >= :endDate)
)
and b.approved = true
and r.roomType = :roomType)