I've got two entities which I want to join via a common 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. The database used is 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
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 开发者_Python百科string contains delete from EVENT_STOCK_VIEW and return an dummy command. 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;
}
精彩评论