如何使用Hibernate映射调整实体之间的关系?

时间:2016-02-21 21:35:01

标签: java hibernate

我有这么简单的计划

enter image description here

以及以下实体:

@Entity
public class Ticket {

    @Id
    @GeneratedValue
    private Integer id;
    @ManyToOne
    private Event event;
    @OneToOne
    private User user;
    @Embedded
    private Seat seat;
    private TicketState state;
    private Float price;
// getters, setters, etc.

@Entity
public class Event {

    @Id
    @GeneratedValue
    private Integer id;
    @OneToOne
    private Movie movie;
    @Embedded
    private Auditorium auditorium;
    private LocalDateTime startDateTime;
    @OneToMany
    private Set<Ticket> tickets = new HashSet<>();
// getters, setters, etc.

@Entity
public class User {

    @Id
    @GeneratedValue
    private Integer id;
    @Enumerated(EnumType.STRING)
    private UserRole role;
    private String name;
    private String email;
    private Instant birthday;
    @OneToMany
    private List<Ticket> tickets = new ArrayList<>();
    private boolean lucky;
// getters, setters, etc.

@Embeddable
public class Auditorium {

    private Integer id;
    private String name;
    private Integer seatsNumber;
    @ElementCollection
    private List<Integer> vipSeats;
// getters, setters, etc.

这些实体也被添加到hibernate.cfg.xml。 比我运行应用程序我有以下例外:

Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: com.epam.spring.core.domain.Event column: id (should be mapped with insert="false" update="false")

乍一看,我没有在Event中看到任何重复,如异常中所述。根据我的方案,我应该在实体映射描述中解决问题?谢谢!

2 个答案:

答案 0 :(得分:1)

willTransitionEvent都映射到名为Auditorium的列。

id中指定其他列名,或在Auditorium中使用@AttributeOverride覆盖默认名称。

答案 1 :(得分:0)

当您使用注释映射实体时,您不需要在hibernate.cfg.xml上重复自己。尝试删除它,再次运行您的代码。

根据Dragan Bozanovic更新我的答案,Auditorium不应该有@Id带注释的字段(但我们无法从你的代码中看到它,如果有的话)。