Skip to content
Advertisement

Spring Data Jpa Repository not saving entities to database

Im having some difficulties using jpa. Im not getting any exceptions, but I cant save anything to the database. I went from Hibernate to Jpa and everything worked perfectly there. Below are my Files

application.properties:

logging.level.org.springframework.web=DEBUG
logging.level.ch.generali=DEBUG
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE

spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=postgres
spring.datasource.password=1234
spring.datasource.url=jdbc:h2:mem:party;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=MYSQL
spring.jpa.hibernate.ddl-auto=update

Model:

@Getter
@Setter
@Builder
public class NewClientFormWrapper {
   //Entity
   NaturalPerson person;
   //Entity
   Address[] addresses;
   //Entity
   CommunicationChannel[] communicationChannels;

}

Repository:

public interface NaturalPersonRepository extends JpaRepository<NaturalPerson, Integer> {

    Optional<List<NaturalPerson>> getNaturalPersonByFirstname(String inputFirstname);

    Optional<NaturalPerson> getNaturalPersonById(int id);

    void deleteNaturalPersonById(int id);

}

Service:

@RestController
@RequestMapping("/partner")
public class PartnerService {

@Autowired
NaturalPersonRepository naturalPersonRepository;

@PostMapping(value = "/client")
@Transactional
public ResponseEntity<NewClientFormWrapper> newClient(@RequestBody @Valid NewClientFormWrapper 
request) {

    request.getPerson().setAddresses(Arrays.asList(request.getAddresses()));
    request.getPerson().setCommunicationChannels(Arrays.
       asList(request.getCommunicationChannels()));
    NaturalPerson naturalPerson = naturalPersonRepository.save(request.getPerson());

    NewClientFormWrapper response = NewClientFormWrapper.builder()
            .person(naturalPerson)
            .addresses(naturalPerson.getAddresses().toArray(new Address[0]))
            .communicationChannels(naturalPerson.getCommunicationChannels().toArray(new 
             CommunicationChannel[0]))
            .build();
    return ResponseEntity.ok(response);
    }
  }

I’m getting a 200 Response when submitting the form, but can’t find the data in the database

Advertisement

Answer

You are using a run time database(H2) so when you are calling APi data is showing from memory. No data is persisted in actual database. To persist the data in actual database you need to set the below properties with actual database url and driver

spring.datasource.url=jdbc:h2:mem:party;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=MYSQL
spring.datasource.driver-class-name=org.h2.Driver
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement