我有一个 POJO 类:
@Entity
@Table(name = "interruttori", catalog = "SMARTPARK")
public class Interruttore implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private int idInterruttore;
private int numeroInterruttore;
private String nomeInterruttore;
private String descrizione;
private List<Luce> luci;
private String pinName;
private boolean remoto;
private boolean stato;
private Date dateTime;
private Set<Integer> activeSensors = new HashSet<Integer>();
//getters and setters and specifically
@Transient
public Set<Integer> getActiveSensors() {
return activeSensors;
}
public void setActiveSensors(Set<Integer> activeSensors) {
this.activeSensors = activeSensors;
}
它是@Transient,因为我不想保留该集合,我需要它只是作为 Controller 中的“计数器”。
我们需要的 Controller 部分是:
@RequestMapping(value="/sensoristica")
public ResponseEntity<Sensoristica> findIlluminazione(@RequestParam(value="idLuce") int idLuce,
@RequestParam(value="lit") boolean lit,
@RequestParam(value="suServer") boolean suServer) {
Sensoristica sensoristica = new Sensoristica();
Luce luce = luceService.findById(idLuce);
String nomeLuce = luce.getNomeLuce();
int numeroLuce = luce.getNumeroLuce();
sensoristica.setLuce(luce);
sensoristica.setLit(lit);
sensoristicaService.saveSensoristica(sensoristica);
logger.debug("Aggiornato sensore " + numeroLuce + " ("+nomeLuce+") acceso: "+lit);
//aggiorniamo lo stato del sensore
luce.setLit(lit);
luceService.updateLuce(luce);
//qui gestisco l'interruttore
if(suServer){
int idInterruttore = luce.getInterruttore().getIdInterruttore();
Interruttore interruttore = interruttoreService.findById(idInterruttore);
Set<Integer> activeSensors = interruttore.getActiveSensors();
logger.debug("Active sensor è " +activeSensors);
if(lit){
activeSensors.add(idLuce);
logger.debug("Aggiungo id "+idLuce);
logger.debug("Active è lungo: "+activeSensors.size());
} else {
if (activeSensors.contains(idLuce)){
activeSensors.remove(idLuce);
logger.debug("Rimuovo id "+idLuce);
logger.debug("Active è lungo: "+activeSensors.size());
}
}
interruttore.setActiveSensors(activeSensors);
interruttoreService.updateInterruttore(interruttore);
boolean canShutDown = activeSensors.isEmpty();
logger.debug("canShutDown is "+canShutDown);
基本上,我想向集合中添加或删除idLuce
,然后检查是否activeSensors.isEmpty()
。
问题是每次对 Controller 的调用都会返回一个空 Set,而不是包含之前的 idLuce 的 Set。
我怎样才能获得它?
最佳答案
其实@Transient应该根据AccessType来应用。
请尝试将@Transient 设置为该字段。
@Transient
private Set<Integer> activeSensors = new HashSet<Integer>();
关于java - Spring Boot + Hibernate - 如何维护 @Transient 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37237688/