自动将数据从另一个表插入并更新到SQL表中

时间:2019-05-16 07:43:22

标签: spring-boot jpa spring-jdbc

我有2个表,我想用数据更新第一个表,然后第二个表将自动更新。 我是春季靴的初学者,我真的需要您的帮助。

我可以将表1中的数据插入表2中,但是如果我更新表1中的某些数据,那么表2将无法更新。

我该怎么办?

这是我到目前为止所做的:表的两个实体以及我用来将数据从表1插入表2的服务。

表1:

  @Entity
  @Table(name = "formation")
   public class Formation {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String cursus;
private String groupeaction;
private String module;
private String formateur;
@Temporal(TemporalType.DATE)
private Date date;
private Long nbrappart;
private Long nbrabsent;
private Long hf;
private Long jf;
private Long nbrheures;
private Long tauxh;
private Long ristourneprevis;
private Long couthebergttc;
private Long coutpausecafttc;

表2:

   @Entity
   @Table(name = "tablef")
   public class Tablef {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String cursus;
private Long nbrappart;
    private Long Sumnbrheures;
    private Long Sumjf;
    private Long jhf;
    private String groupeaction;

我使用的服务:

public Boolean InserIntoTableF(Tablef tf) {
Long id = ThreadLocalRandom.current().nextLong();
tf.setId(id);
jdbc.execute("insert into tablef (id,cursus,groupeaction 
   ,nbrappart,sumnbrheures,sumjf,jhf)\r\n" + 
"select   id,cursus,groupeaction,nbrappart,sum(nbrheures),sum(jf) 
            ,sum(jf)*nbrappart\r\n" + 
        " from formation \r\n" + 
        "group by cursus ;");
return true;


}

控制器:

  @CrossOrigin(origins = "*", maxAge = 3600)
  @RestController
 @RequestMapping("/api")
  @PreAuthorize("hasRole('ADMIN')")
 public class FormationController {
  @Autowired
  private FormationService formationservice;

  @Autowired
   private FormationRepository formationrepository;
 @GetMapping("/formations")
public List<Formation> GetAll() {
    return formationrepository.findAll();
}

@GetMapping("/formations/{id}")
public ResponseEntity<Formation> getFormationById(@PathVariable(value = "id") Long formationId)
        throws ResourceNotFoundException {
    Formation formation = formationrepository.findById(formationId)
            .orElseThrow(() -> new ResourceNotFoundException("Formation not found for this id :: " + formationId));
    return ResponseEntity.ok().body(formation);
}

@PostMapping("/formations")
public Formation createFormation(@Valid @RequestBody Formation formation) {
    return formationrepository.save(formation);
}
// this is how i update my entity formation (table 1)
@PutMapping("/formations/{id}")
public ResponseEntity<Formation> updateFormation(@PathVariable(value = "id") Long formationId,
        @Valid @RequestBody Formation formationDetails) throws ResourceNotFoundException {
    Formation formation = formationrepository.findById(formationId)
            .orElseThrow(() -> new ResourceNotFoundException("Formation not found for this id :: " + formationId));

    formation.setCursus(formationDetails.getCursus());
    formation.setGroupeaction(formationDetails.getGroupeaction());
    formation.setModule(formationDetails.getModule());
    formation.setFormateur(formationDetails.getFormateur());
    formation.setDate(formationDetails.getDate());
    formation.setNbrappart(formationDetails.getNbrappart());
    formation.setNbrabsent(formationDetails.getNbrabsent());
    formation.setHf(formationDetails.getHf());
    formation.setJf(formationDetails.getJf());
    formation.setNbrheures(formationDetails.getNbrheures());
    formation.setTauxh(formationDetails.getTauxh());
    formation.setRistourneprevis(formationDetails.getRistourneprevis());
    formation.setCouthebergttc(formationDetails.getCouthebergttc());
    formation.setCoutpausecafttc(formationDetails.getCoutpausecafttc());
    final Formation updatedFormation = formationrepository.save(formation);
    return ResponseEntity.ok(updatedFormation);
}

@DeleteMapping("/formations/{id}")
public Map<String, Boolean> deleteFormation(@PathVariable(value = "id") Long formationId)
        throws ResourceNotFoundException {
    Formation formation = formationrepository.findById(formationId)
            .orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + formationId));

    formationrepository.delete(formation);
    Map<String, Boolean> response = new HashMap<>();
    response.put("deleted", Boolean.TRUE);
    return response;
}
@PostMapping(value = "/fileupload")
public ResponseEntity<Formation> uploadFile(@ModelAttribute Formation formation) {

    Boolean isFlag=formationservice.saveDataFromFile(formation.getFile());
    if(isFlag) {
        return new ResponseEntity<>(HttpStatus.OK);

    }else

    return   new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
  // here where i inser data from formation(table1) to tablef (table2)
   @PostMapping(value = "/test")
 public Boolean AddTf(Tablef tf) {
  return formationservice.InserIntoTableF(tf);

}

}

2 个答案:

答案 0 :(得分:0)

如果您使用spring boot jpa持久化数据,那么可以看看JPA EntityListener和@PostPersist

@Entity
@EntityListeners(MyEntityListener.class)
public class MyEntity {
  @Id
  @GeneratedValue
  private int id;

  private String field;

  public MyEntity() { }


}

MyEntityListener隐含

public class MyEntityListener {


  @PostPersist
  void onPostPersist(MyEntity myEntity) {
      // save data to second table that needs an update on myEntity save 
  }

}

答案 1 :(得分:0)

最好在数据库中编写sql触发器,以将记录从一个表插入并更新到另一个表。 如以下链接所述。   MYSQL Triggers