[英]Using a view as a join table with Hibernate
I've got two entities which I want to join via a common String. 我有两个实体,我想通过一个普通的String加入。 I've created a view which I want to use as the join table.
我创建了一个我想用作连接表的视图。 This all works fine except for when I try to delete an entity.
除了当我尝试删除实体时,这一切都正常。 Hibernate then tries to delete from that view which of course fails.
然后Hibernate尝试从该视图中删除当然失败的视图。 The database used is MySQL.
使用的数据库是MySQL。
So I've got 所以我有
@Entity
public class Event {
...
String productId;
Date eventDatetime;
...
}
@Entity
public class Stock {
...
String productId;
...
}
I've created a view in MySQL 我在MySQL中创建了一个视图
DROP VIEW IF EXISTS EVENT_STOCK_VIEW;
create view EVENT_STOCK_VIEW AS
SELECT EVENT.EVENT_ID, STOCK.STOCK_ID
FROM EVENT, STOCK
where STOCK.PRODUCT_ID = EVENT.PRODUCT_ID;
in Event I've added: 在事件我添加:
@ManyToOne(fetch=FetchType.LAZY)
@JoinTable(name="EVENT_STOCK_VIEW",
joinColumns=@JoinColumn(name="EVENT_ID"),
inverseJoinColumns=@JoinColumn(name="STOCK_ID",updatable=false,insertable=false))
public Stock getStock(){
return this.stock;
}
and in Stock: 和库存:
@OneToMany(fetch=FetchType.LAZY)
@JoinTable(name="EVENT_STOCK_VIEW",
joinColumns=@JoinColumn(name="STOCK_ID",updatable=false,insertable=false), inverseJoinColumns=@JoinColumn(name="EVENT_ID",updatable=false,insertable=false))
@OrderBy("eventDatetime DESC")
public List<Event> getEvents(){
return events;
}
I've googled a bit and found this site . 我用谷歌搜索了一下这个网站 。 But the solution isn't really that nice (you have to use entity in between stock and event).
但解决方案并不是那么好(你必须在股票和事件之间使用实体)。
Are there any other solutions? 还有其他解决方案吗?
I could use a Hibernate Interceptor and override onPrepareStatement(String sql) and check whether the SQL string contains delete from EVENT_STOCK_VIEW and return an dummy command. 我可以使用Hibernate Interceptor并覆盖onPrepareStatement(String sql)并检查SQL字符串是否包含来自EVENT_STOCK_VIEW的删除并返回一个虚拟命令。 Clearly a hack which I try to avoid.
显然是我试图避免的黑客攻击。
Can't you do it without join table at all? 如果没有连接表,你能不能这样做? As far as I understand, your relationship is effectively read-only, so that the following approach should work fine:
据我了解,您的关系实际上是只读的,因此以下方法应该可以正常工作:
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "productId",
referencedColumnName = "productId", insertable = false, updateable = false)
public Stock getStock(){
return this.stock;
}
...
@OneToMany(fetch=FetchType.LAZY, mappedBy = "stock")
@OrderBy("eventDatetime DESC")
public List<Event> getEvents(){
return events;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.