我有父母 - >儿童关系,@ManyToOne
/ @OneToMany
关系。
我正在处理对父代的更新,代码大致如下:
运行时,我发现发生以下序列
DataIntegrityViolationException
被抛出,因为来自第二次更新的孩子再次被插入。我认为这必须与父缓存的事实有关,而不是从数据库返回。我不确定这里的正确过程应该是什么。
相关信息:
@Transactional
的测试中最初没有失败。 (一个难得的教训)什么是正确的处理方式 - 特别是,为了避免每次都从数据库中加载Parent,同时仍然正确跟踪子实体?
代码示例如下所示。
@Entity // Parent
class Fixture {
@OneToMany(cascade=CascadeType.ALL, mappedBy="fixture", fetch=FetchType.EAGER) @Getter @Setter
@MapKey(name="instrumentPriceId")
private Map<String,Instrument> instruments = Maps.newHashMap();
private Instrument addInstrument(Instrument instrument)
{
instruments.put(instrument.getInstrumentPriceId(), instrument);
instrument.setFixture(this);
log.info("Created instrument {}",instrument.getInstrumentPriceId());
return instrument;
}
/**
* Returns an instrument with the matching instrumentId.
* If the instrument does not exist, it is created, appended to the internal collection,
* and then returned.
*
* This method is guaranteed to always return an instrument.
* This method is thread-safe.
*
* @param instrumentId
* @return
*/
public Instrument getInstrument(String instrumentId)
{
if (!instruments.containsKey(instrumentId))
{
addInstrument(new Instrument(instrumentId));
}
return instruments.get(instrumentId);
}
}
@Entity // Child
public class Instrument {
@Column(unique=true)
@Getter @Setter
private String instrumentPriceId;
@ManyToOne(optional=false)
@Getter @Setter @JsonIgnore
private Fixture fixture;
public Instrument(String instrumentPriceId)
{
this.instrumentPriceId = instrumentPriceId;
}
}
并且,更新处理器代码:
class Processor {
@Autowired
@Qualifier("FixtureCache")
private Ehcache fixtureCache;
@Autowired
private FixtureRepository fixtureRepository;
void update(String fixtureId, String instrumentId) {
Fixture fixture = getFixture(fixtureId);
// Get the instrument, creating it & appending
// to the collection, if it doesn't exist
fixture.getInstrument(instrumentId);
// do some updates...ommitted
fixtureRepository.save(fixture);
fixtureCache.put(new Element(fixtureId, fixture));
}
/**
* Returns a fixture.
* Returns from the cache first, if present
* If not present in the cache, the db is checked.
* Finally, if the fixture does not exist, a new one is
* created and returned
*/
Fixture getFixture(String fixtureId) {
Fixture fixture;
Element element = fixtureCache.get(fixtureId);
if (element != null)
{
fixture = element.getValue();
} else {
fixture = fixtureRepostiory.findOne(fixtureId);
if (fixture == null)
{
fixture = new Fixture(fixtureId);
}
}
return fixture;
}
}
答案 0 :(得分:1)
答案很简单。
在update
方法中,我忽略了save()
操作的结果。
通常,如果您不打算再次使用对象,这很好。 (这很常见,因为你在工作单元结束时保存)。
然而,当我继续使用我的'父母'时,我需要观察返回的值:
所以这个:
fixtureRepository.save(fixture);
fixtureCache.put(new Element(fixtureId, fixture));
成为这个:
fixture = fixtureRepository.save(fixture);
fixtureCache.put(new Element(fixtureId, fixture));