当我使用复合主键的@EmbeddedId
注释向表中添加条目时,我想学习休眠基础知识并且不理解为什么我的应用程序不起作用:
代表PK的类:
@Embeddable
public class OHLCVKey implements Serializable{
private static final long serialVersionUID = -3996067621138883817L;
@Column(name="Symbol")
protected String symbol;
@Column(name="Currency")
protected String currency;
@Column(name="Datum")
protected java.sql.Date datum;
public OHLCVKey() {}
public OHLCVKey(String symbol, String currency, Date datum) {
super();
this.symbol = symbol;
this.currency = currency;
this.datum = datum;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public java.sql.Date getDatum() {
return datum;
}
public void setDatum(java.sql.Date endTime) {
this.datum = endTime;
}
@Override
public String toString() {
return String.format("OHLCKey: {%s %s %s}", symbol, currency, datum);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (symbol == null ? 0 : symbol.hashCode());
result = prime * result + (currency == null ? 0 : currency.hashCode());
result = prime * result + (datum == null ? 0 : datum.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if(obj != null || !(obj instanceof OHLCVKey)) {
OHLCVKey other = (OHLCVKey) obj;
boolean sameSymbol = this.symbol.equals(other.symbol);
boolean sameCurrency = this.currency.equals(other.currency);
boolean endTime = this.datum.equals(other.datum);
return sameSymbol && sameCurrency && endTime;
}
return false;
}
}
持久班:
@Entity
@Table(name = "ohlcv_data")
public class OHLCV implements Serializable {
/**
*
*/
private static final long serialVersionUID = -742762046516249869L;
@EmbeddedId
protected OHLCVKey key;
@Column(name = "Exchange")
private String exchange;
@Column(name = "Open")
private double open;
@Column(name = "High")
private double high;
@Column(name = "Low")
private double low;
@Column(name = "Close")
private double close;
@Column(name = "Volume")
private long volume;
public OHLCV() {};
public OHLCV(OHLCVKey key) {
super();
this.key = key;
}
public OHLCV(OHLCVKey key, String exchange, double open, double high, double low, double close, long volume) {
super();
this.key = key;
this.exchange = exchange;
this.open = open;
this.high = high;
this.low = low;
this.close = close;
this.volume = volume;
}
public OHLCVKey getKey() {
return key;
}
public void setKey(OHLCVKey key) {
this.key = key;
}
public String getExchange() {
return exchange;
}
public void setExchange(String exchange) {
this.exchange = exchange;
}
public double getOpen() {
return open;
}
public void setOpen(double open) {
this.open = open;
}
public double getHigh() {
return high;
}
public void setHigh(double high) {
this.high = high;
}
public double getLow() {
return low;
}
public void setLow(double low) {
this.low = low;
}
public double getClose() {
return close;
}
public void setClose(double close) {
this.close = close;
}
public long getVolume() {
return volume;
}
public void setVolume(long volume) {
this.volume = volume;
}
}
我假设在创建OHLC实例之后,可以使用以下函数(在名为OHLCVDataManager
的类中)将其数据添加到数据库表中:
public void addOHLCV(OHLCV ohlcv) { // line 50
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.save(ohlcv); // line 55
tx.commit();
log.info("Added {} to database!", key.toString());
} catch(Exception e) {
if(tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
System.exit(2); //TODO remove, exit Spring application
}
}
但是我得到了带有堆栈跟踪的以下PropertyAccessException / IllegalArgumentException:
org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [protected OHLCVKey OHLCV.key] by reflection for persistent property [OHLCV#key] : OHLCV@46479254
2018-11-03 18:43:57.567 INFO 18384 --- [ Thread-9] ConfigServletWebServerApplicationContext : Closing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@7582b66f: startup date [Sat Nov 03 18:43:53 CET 2018]; root of context hierarchy
at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:75)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:224)
at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:4931)
at org.hibernate.mapping.Component$StandardGenerationContextLocator.locateGenerationContext(Component.java:480)
at org.hibernate.id.CompositeNestedGeneratedValueGenerator.generate(CompositeNestedGeneratedValueGenerator.java:93)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:123)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:709)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:701)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:696)
at OHLCVDataManager.addOHLCV(OHLCVDataManager.java:55)
at OHLCVDataManager.addOHLCV(OHLCVDataManager.java:70)
at ServerApplication.main(ServerApplication.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.lang.IllegalArgumentException: Can not set OHLCVKey field OHLCV
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
at java.lang.reflect.Field.get(Field.java:393)
at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:71)
EDIT1:
ohlcvDataManager.addOHLCV("TEST", "USD", new java.sql.Date(2018, 1, 1), "TEST", 1, 1, 1, 1, 1);
// OHLCDataManager#addOHLCV call:
public void addOHLCV(String symbol, String currency, java.sql.Date date,
String exchange, double open, double high, double low, double close, long volume) {
addOHLCV(new OHLCV(new OHLCVKey(symbol,currency, date),exchange, open, high, low, close, volume));
}
EDIT2: 我有带有Java 1.8的testet hibernate-core版本5.3.7和5.4
EDIT2: 我的类路径中只有一个OHLCV类和一个OHLCVKey类,我还尝试过重命名这些类。
答案 0 :(得分:2)
我认为您在用Hibernate 5.0和5.1中映射为EmbededID的复合键遇到了一个bug,应该在5.1.1中已修复 https://hibernate.atlassian.net/browse/HHH-10618
尝试更改休眠版本。我也可以在评论之一中看到@ K.Nicholas在说相同的代码对他有效。这就是为什么我更倾向于认为您遇到了这个错误。
答案 1 :(得分:1)
降级到版本
4.3.11。最终
工作...
答案 2 :(得分:0)
自从我进入休眠状态以来已经有一段时间了,但是从错误中看来它无法访问
[protected OHLCVKey OHLCV.key]
此字段。为了缩小范围,我建议两件事。首先,查看是否可以删除此行OHLCVKey key = (OHLCVKey) session.save(ohlcv); // line 55
中的转换并将其转换为session.save(ohlcv)
,只是为了确定是导致转换的转换还是保存本身。其次,尽管没有多大意义,请尝试将此处的访问修饰符更改为私有。
@EmbeddedId
protected OHLCVKey key;
如果这两个方法都不能解决问题,请尝试使用HQL并查看。
答案 3 :(得分:0)
get(req: Request, res: Response) {
const mongo = new MongoDb();
mongo.connect().then(() => {
const db = mongo.getDb();
const collection = db.collection('todo', (error, collection) => {
if (error) {
res.json(error);
res.statusCode = HttpStatus.BAD_REQUEST
return;
}
collection.find().toArray((error, result) => {
if (error) {
res.json(error);
res.statusCode = HttpStatus.BAD_REQUEST
}
res.json(result);
res.statusCode = HttpStatus.OK;
})
});
mongo.close();
});
}
和平的堆栈跟踪意味着Hibernate尝试为某个对象设置字段值,但是它们的类不兼容:
Caused by: java.lang.IllegalArgumentException: Can not set OHLCVKey field OHLCV
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
at java.lang.reflect.Field.get(Field.java:393)
at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:71)
这意味着Hibernate从不同的类而不是您要保存的对象的类中加载了元数据。请检查您的应用程序的类路径中是否只有一个OHLCV类,因为您提供的示例效果很好。