如何用spring boot更新数据库

问题描述 投票:0回答:1

我试图在我的spring boot应用程序中更新数据库(postgresql)和一些表单信息,这些信息将从Angular 8表单中获取。我怎样才能完成下面的代码呢?

PS : 我没有访问前端开发的权限,所以无法访问Angular代码。

我的实体 :

@Entity
@Data
@Table(name = "person")
@AllArgsConstructor
@NoArgsConstructor
public class PersonEntity implements java.io.Serializable {

    @Id
    @Column(name = "id_person")
    private int idPerson;

    @Column(name = "name")
    private String name;

    @Column(name = "alive")
    private Boolean alive;
}

我的Mapping类。

@Data
public class PersonForm {

    @NotBlank
    private String idPerson;

    @NotBlank
    private String name;

    private boolean alive;

}

我的Repository:我的Repository。

@Repository
public interface IPersonRepository extends JpaRepository<PersonEntity, String> {

}

我的控制器:我的控制器。

@RequestMapping(value = "person")
public class PersonController {

    private final PersonService personService;

    public PersonController(PersonService personService) {this.personService = personService;}

    @PostMapping(value = "savePerson")
    @ResponseBody
    public ResponseEntity<PersonEntity> savePerson(@RequestBody final PersonForm form) {

        return ?
    }
}

我的服务。

@Transactional
@Service
public class PersonService {

    @Autowired
    private IPersonRepository personRepository;

    public IPersonRepository(IPersonRepository personRepository) {
        this.personRepository = personRepository;
    }
java angular spring postgresql spring-boot
1个回答
0
投票

也许这就够用了。

有其他的方法,这只是补充你思路的例子。

如果你得到一个编译错误或其他错误,让我知道:)

首先你需要创建你的对象 PersonEntity 并将其发送给你的服务。

@RequestMapping(value = "person")
public class PersonController {

    private final PersonService personService;

    public PersonController(PersonService personService) {this.personService = personService;}

    @PostMapping(value = "savePerson")
    @ResponseBody
    public ResponseEntity<PersonEntity> savePerson(@RequestBody final PersonForm form) {

        PersonEntity entity = new PersonEntity(form);
        entity = personService.save(entity);
        return ResponseEntity.ok(entity);

    }
}

在您的服务中,您将调用 save 方法。

@Transactional
@Service
public class PersonService {

    @Autowired
    private IPersonRepository personRepository;

    public IPersonRepository(IPersonRepository personRepository) {
        this.personRepository = personRepository;
    }

    public PersonEntity save(PersonEntity entity) {
        return personRepository.save(entity);
    }

}

之后你将创建 ResponseEntity 在该方法中 PersonController.savePerson

© www.soinside.com 2019 - 2024. All rights reserved.