是否可以为双向关系创建一列?
我的实体:
@Entity
@Table(name = "subscription")
@Proxy(lazy = false)
public class Subscription {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "subscription_id")
private long id;
@Column(name = "userid", nullable = false)
private String userId;
@Column(name = "saledate", nullable = false)
@Temporal(TemporalType.DATE)
private Date saleDate;
@Column(name = "finishdate", nullable = false)
@Temporal(TemporalType.DATE)
private Date finishDate;
@Column(name = "price", nullable = false)
private long price;
@Column(name = "description", nullable = false)
private String description;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "subscription")
private List<VisitDate> visitDates = new ArrayList<>();
}
@Entity
@Table(name="visitdate")
public class VisitDate {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id")
private long id;
private long subscription;
@Column(name = "date", nullable = false)
@Temporal(TemporalType.DATE)
private Date date;
@ManyToOne
@JoinColumn(name="subscription_id")
private Subscription associatedSub;
}
现在我看到数据库中有两列,有点混乱。
我不想保存相同的数据,但想显示一个关于某一天有多少用户访问的报告。
更新:
2条答案
按热度按时间cgh8pdjw1#
您不需要在visitdate类中创建单独的字段“subscription”。hibernate将自动创建一个字段来存储订阅id。代码需要稍微更改。
请注意,我已将mappedby属性更改为指向上述类中的associatedsub。
ckocjqey2#
你可以使用单向关系来达到同样的目的。您只需要为特定的订阅添加一个访问列表/访问集,而不必为特定的访问创建一个订阅列表。参考请访问[java jpa]:(https://en.wikibooks.org/wiki/java_persistence/onetomany#undirectional_onetomany.2c_no_inverse_manytoone.2c_no_join_table_.28jpa_2.0_only.29)!