【问题标题】:Spring one to one relationship弹簧一对一的关系
【发布时间】:2019-09-27 16:59:57
【问题描述】:

我有一个非常简单的问题。我不知道我是否不明白某些事情,或者我不知道该怎么做。 我一直想知道如何在冬眠的春天一对一。我可以从两个方向到达桌子。 假设我有 Hotel 和 hotelDetails 表。 正在为我创建一个密钥,以便我可以从酒店到达 hotelRating,但我不能走另一条路。 有时它对我很重要。 我将使用示例代码。

public class Hotel {

    private Long id;
    private String name;
    private String currency;
    private String image;
    private HotelRating hotelRating;


    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
.
    .
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "hotel_rating_id", referencedColumnName = "id")
    public HotelRating getHotelRating() {
        return hotelRating;
    }

    public void setHotelRating(HotelRating hotelRating) {
        this.hotelRating = hotelRating;
    }

酒店评级表。

问题是,当我试图让 getter 和 setter 做酒店时。我得到了:

org.springframework.beans.factory.BeanCreationException:在类路径资源 [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class] 中定义名称为“entityManagerFactory”的 bean 创建错误:调用 init 方法失败;嵌套异常是 javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory;嵌套异常是 org.hibernate.MappingException:无法确定类型:com.flightradar.flightradar.model.hotel.Hotel,表:hotel_rating,列:[org.hibernate.mapping.Column(hotel)]

@Entity
@Table(name = "hotel_rating")
public class HotelRating {

    private long id;

    private Integer votesNumber;

    @Min(1)
    @Max(5)
    private Double average;

    @OneToOne(mappedBy = "hotel_rating")
    Hotel hotel;



    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public Integer getVotesNumber() {
        return votesNumber;
    }

    public void setVotesNumber(Integer votesNumber) {
        this.votesNumber = votesNumber;
    }

    public Double getAverage() {
        return average;
    }

    public void setAverage(Double average) {
        this.average = average;
    }

}

所以,各位帮我了解从 HotelRating Table 到 Hotel 表的最简单方法。 例如,我有 HotelRating 列表,我必须从 Hotel 表中获取每个 hotelRanking 对象。

【问题讨论】:

  • Hotel 类中是否有一个名为hotel_rating 类型为HotelRating 的Java 属性?异常表明情况并非如此。

标签: java spring hibernate jpa one-to-one


【解决方案1】:

HotelRating 类中的“mappedBy”值必须提供

拥有关系的字段。

在您的示例中,值为“hotel_rating”

 @OneToOne(mappedBy = "hotel_rating")
 Hotel hotel;

但是Hotel 类中没有这样的字段。对应的字段可能是“hotelRating”。

【讨论】:

  • 哦,谢谢 :D 原来如此简单!
猜你喜欢
  • 2018-07-22
  • 1970-01-01
  • 2015-09-02
  • 1970-01-01
  • 1970-01-01
  • 2020-02-24
  • 2016-07-09
  • 1970-01-01
  • 2022-11-17
相关资源
最近更新 更多