Dao class don't perform insert or update on spring-boot application

1.4k Views Asked by At

In my current spring-boot application, I have this hibernate configuration:

# jdbc.X
spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/mystore?charSet=LATIN1
spring.datasource.username=klebermo
spring.datasource.password=123

# hibernate.X
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=create-drop

which create the database tables and insert the data from data.sql without problems, but when I try insert or update an entity through a view, no data is inserted, despite no error is triggered.

the submission from the form is handled by this methods from my controller:

  @RequestMapping(value = "cadastra", method=RequestMethod.POST)
  @ResponseBody
  public void cadastra(@ModelAttribute("object") E object, BindingResult result) {
    serv.cadastra(object);
  }

  @RequestMapping(value = "altera", method=RequestMethod.POST)
  @ResponseBody
  public void altera(@ModelAttribute("object") E object, BindingResult result) {
    serv.altera(object);
  }

  @RequestMapping(value = "remove", method=RequestMethod.POST)
  @ResponseBody
  public void remove(@ModelAttribute("object") E object, BindingResult result) {
    serv.remove(object);
  }

in my service class I have:

  @PreAuthorize("hasPermission(#user, 'cadastra_'+#this.this.name)")
  @Transactional
  public void cadastra(E object) {
    dao.insert(object);
  }

  @PreAuthorize("hasPermission(#user, 'altera_'+#this.this.name)")
  @Transactional
  public void altera(E object) {
    dao.update(object);
  }

  @PreAuthorize("hasPermission(#user, 'remove_'+#this.this.name)")
  @Transactional
  public void remove(E object) {
    dao.delete(object);
  }

and in my dao class:

@Transactional
public void insert(E object) {
    getEntityManager().persist(object);
}

@Transactional
public void update(E object) {
    getEntityManager().merge(object);
}

@Transactional
public void delete(E object) {
    getEntityManager().remove(object);
}

anyone can see what's wrong here?

1

There are 1 best solutions below

1
On BEST ANSWER

I managed to fix this pŕoblem using this structure to the methods of my dao class:

public void insert(E object) {
    EntityManager entityManager = getEntityManager();
    entityManager.getTransaction().begin();
        entityManager.persist(object);
    entityManager.getTransaction().commit();
}