В какой-то момент мое приложение прекратило сохранение значения boolean
для @Entity
при сохранении моим Repository
.Spring JPA/Hibernate не обновляется до DB для изменения логического значения для @Entity при сохранении
A REST
звонок сделан, в пределах этого звонка я установил Device
как InUse
в true.
device.setInUse(inUse);
Device savedDev = deviceRepository.save(device);
Logger.debug("Device after save isInUse() " + savedDev.isInUse());
Thread.sleep(5000);
Device dbDev2 = deviceRepository.findOne(device.getSerial());
Logger.debug("Device again from db for isInUse() " + dbDev2.isInUse());
Выходной сигнал этого является true
как для устройства сохраняются и при выдаче deviceRepository.findOne(device.getSerial())
. Проблема в том, что когда я перехожу в базу данных и фактически просматриваю запись, она не обновляется.
Я включил ведение журнала отладки в спящем режиме, и я не вижу обновления, сделанные на устройстве. Когда я сохраняю другие @Entity
, я могу увидеть запрос на спящий режим в журналах. Это заставляет меня думать, что это как-то кэширует это.
В журналах Hibernate я вижу
- Родительский объект, который содержит список устройств, которые загружаются из спящего режима
- (Это где устройство затем должно быть обновлено с InUse = TRUE)
- продолжает загружать другие детали из спящего режима для списков
@Entity
«с от родителей, но никогда не обновляет устройство ...
Q uestion
Я хотел знать, что может быть причиной этого?
Rest Контроллер
@RestController
@Transactional(propagation = Propagation.REQUIRED)
public class HomeController {
@Autowired
private DeviceRepository deviceRepository;
/**
* Default index
*
* @return
*/
@RequestMapping(value = "/")
public String index() {
return "index";
}
@RequestMapping(value = "runTestRun", method = RequestMethod.POST)
public ResponseEntity<String> runTestRun(@RequestBody String jsonObject) throws Exception {
.....
setDevicesInUse(testRun.getDevices(), true);
.....
}
private void setDevicesInUse(Set<Device> devices, boolean inUse) throws InterruptedException {
for (Device device : devices) {
Logger.debug("Marking Device " + device.getSerial() + " " + device.getReadableName() + " InUse to " + inUse);
Device dbDev = deviceRepository.findOne(device.getSerial());
Logger.debug("Device before change checking isInUse() " + dbDev.isInUse());
dbDev.setInUse(inUse);
Logger.debug("Device after setting isInUse() " + dbDev.isInUse());
device.setInUse(inUse);
Device savedDev = deviceRepository.save(device);
Logger.debug("Device after save isInUse() " + savedDev.isInUse());
Thread.sleep(2000);
Device dbDev2 = deviceRepository.findOne(device.getSerial());
Logger.debug("Device again from db for isInUse() " + dbDev2.isInUse());
Thread.sleep(2000);
}
}
Application.properties
# DataSource settings: set here your own configurations for the database
# connection.
spring.datasource.url: jdbc:mysql://localhost/xxx
spring.datasource.username=xxx
spring.datasource.password=xxx
spring.datasource.driverClassName=com.mysql.jdbc.Driver
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
# Use hibernates new generator mappings, this is used for the appium port using a TABLE generator
spring.jpa.properties.hibernate.id.new_generator_mappings=true
# Web server
spring.data.rest.base-path=/api
server.context-path=/api
server.port=8082
# TODO FOR DEBUG ONLY
spring.thymeleaf.cache=false
spring.freemarker.cache=false
spring.groovy.template.cache=false
spring.velocity.cache=false
spring.mustache.cache=false
server.session.persistent=true
spring.h2.console.enabled=true
spring.resources.cache-period=0
Я попытался добавить следующее, но это не имеет никакого значения
spring.jpa.properties.hibernate.cache .use_second_level_cache = false spring.j pa.properties.hibernate.cache.use_query_cache = ложь
Устройство
@Data
@Entity
@Table(name = "device")
public class Device {
private @Id String serial;
private boolean active;
private boolean inUse;
private @Version @JsonIgnore Long version;
private Device() {
}
После беглого взгляда пахнет вопросом о границах транзакции. – chrylis
@chrylis Я вижу, что родительский объект загружается из спящего режима, а затем там, где он должен ничего не сохранять, ничего не происходит. Когда я перезагружаю устройство из репозитория, он показывает, как он обновляется, но не было никаких журналов спящего режима, чтобы показать мне, что он фактически устанавливает устройство inUse или фактически извлекает сохраненное устройство из БД. – ALM