我试图在Spring MVC应用程序中连接到我的数据库。有两张桌子。用户和订单,用户有一个主键列:“userID”,订单具有来自列的复合键:“userID”和“orderID”,其中userID是引用Users表中“userID”列的外键。
以下是我的课程:
订单:
@Entity
@Table(name = "Orders")
@IdClass(OrderPK.class)
public class Order implements Serializable{
private static final Long serialVersionUID = 1L;
@EmbeddedId
private OrderPK orderPK;
//other properties
//no args and full args constructor
//getters and setters
//toString
}
OrderPK:
@Embeddable
public class OrderPK implements Serializable {
@Column(name = "orderID")
private Long orderID;
@ManyToOne
@JoinColumn(name = "userID")
private User user;
public OrderPK() {
}
public OrderPK(Long orderID, User user) {
this.orderID = orderID;
this.user = user;
}
public Long getOrderID() {
return orderID;
}
public void setOrderID(Long orderID) {
this.orderID = orderID;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof OrderPK)) return false;
OrderPK that = (OrderPK) o;
return Objects.equals(getOrderID(), that.getOrderID()) &&
Objects.equals(getUser(), that.getUser());
}
@Override
public int hashCode() {
return Objects.hash(getOrderID(), getUser());
}
}
用户:
@Entity
@Table(name = "USERS")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name="USER_SEQUENCE", sequenceName="USER_SEQUENCE")
@GeneratedValue(strategy=GenerationType.SEQUENCE,
generator="USER_SEQUENCE")
@Column(name = "userid")
private Long userId;
//other properties
//no args and full args constructor
//getters and setters
//toString
}
当我尝试连接到数据库时,我得到以下异常:
org.springframework.beans.factory.BeanCreationException:在类路径资源中定义名称为'entityManagerFactory'的bean时出错[org / springframework / boot / autoconfigure / orm / jpa / HibernateJpaAutoConfiguration.class]:init方法的调用失败;嵌套异常是org.hibernate.AnnotationException:无法在使用@IdClass注释的实体中查找属性(orderID,user):com.ex.evemarketback.domain.Order
...
引起:org.hibernate.AnnotationException:无法在使用@IdClass注释的实体中找到属性(orderID,user):com.ex.evemarketback.domain.Order
有什么建议吗?
答案 0 :(得分:0)
当您使用@EmbeddedId
时,您不需要@IdClass
注释:
@Entity
@Table(name = "Orders")
public class Order implements Serializable{
或者如果你想保留@IdClass
:
// @Embeddable - no need for that
public class OrderPK implements Serializable {
private Long orderID;
private Long userId;
...
}
实体:
@Entity
@Table(name = "Orders")
@IdClass(OrderPK.class)
public class Order implements Serializable{
@Id
@Column(name = "orderID")
private Long orderID;
@Id
@Column(name = "userId", insertable=false, updatable=false)
private Long userId;
@ManyToOne
@JoinColumn(name = "userID")
private User user;