Hibernate's sessionFactory not deleting an object from DB












0














No idea why this is not working !!



I'm trying to delete a credential from my database but the delete method is not helping ...



This is how I'm doing it:



So this is triggering when the user clicks a button in the page:



$("#credentialsTable").on('click',"button[id^='del-']",  (e) => {
var credentialId = e.target.id;
console.log('credId' + credentialId);
$.post( "/fisicHost/" + credentialId + "/credentials", data => {
console.log(data);
});
});


The post is being handled by this controller's method:



@RestController
public class Controlador {

@Autowired
private FisicHostDao fisicHostDao;
@Autowired
private CredentialDao credentialDao;

@RequestMapping(value = "/fisicHost/{id}/credentials", method = RequestMethod.POST)
public String deleteCredential(@PathVariable(value = "id") String credId){
String parts = credId.split("-");
int id = Integer.parseInt(parts[1]);
Credential c = credentialDao.getCredentialById(id);
credentialDao.delete(c);
return "justreturnsomething";
}

}


This is the Credential class:



@Entity
public class Credential {

@Id
private int id;

@JsonIgnore
@ManyToOne(fetch= FetchType.EAGER)
private FisicHost fisicHost;

private String user;
private String password;
private String notes;
private String role;

public Credential(){

}

public Credential(int id, FisicHost fisicHost, String user, String password, String notes, String role) {
this.id = id;
this.fisicHost = fisicHost;
this.user = user;
this.password = password;
this.notes = notes;
this.role = role;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public FisicHost getFisicHost() {
return fisicHost;
}

public void setFisicHost(FisicHost fisicHost) {
this.fisicHost = fisicHost;
}

public String getUser() {
return user;
}

public void setUser(String user) {
this.user = user;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getNotes() {
return notes;
}

public void setNotes(String notes) {
this.notes = notes;
}

public String getRole() {
return role;
}

public void setRole(String role) {
this.role = role;
}
}


and this is the CredentialDao class:



@Repository
public class CredentialDaoImpl implements CredentialDao {



@Autowired
private SessionFactory sessionFactory;

@Override
public List<Credential> getAllCredentialsByFisicHost(FisicHost fisicHost) {
// Open a session
Session session = sessionFactory.openSession();

Criteria c = session.createCriteria(Credential.class).add(Restrictions.eq("fisicHost.id", fisicHost.getId()));

List<Credential> allCredentials = c.list();

// Close the session
session.close();

return allCredentials;
}

@Override
public Credential getCredentialByUser(String user) {
Session session = sessionFactory.openSession();
Credential credential = session.get(Credential.class, user);
session.close();
return credential;
}

@Override
public Credential getCredentialById(int id) {
Session session = sessionFactory.openSession();
Credential credential = session.get(Credential.class, id);
session.close();
return credential;
}

@Override
public void save(Credential credential) {
Session session = sessionFactory.openSession();
session.save(credential);
session.close();
}

@Override
public void update(Credential credential) {
Session session = sessionFactory.openSession();
session.update(credential);
session.close();
}

@Override
@Transactional
public void delete(Credential credential) {
Session session = sessionFactory.openSession();
session.delete(credential);
session.close();
}


}



Ok, so I'm debuggin the program and I see that when I get to these lines in the controller:



    Credential c = credentialDao.getCredentialById(id);
credentialDao.delete(c);


the credentials that are being loaded are the ones I want to, but the delete is not working ... the credential is not being erased from the DB.



This is a picture of the debugger:



enter image description here



I can see that the credentialDao sessionFactory is = null .... this is a bit weird, might this be the problem ?? If so, why is this a problem if the sessionFactory is annotated as @AutoWired in the CredentialDaoImpl class !



enter image description here










share|improve this question



























    0














    No idea why this is not working !!



    I'm trying to delete a credential from my database but the delete method is not helping ...



    This is how I'm doing it:



    So this is triggering when the user clicks a button in the page:



    $("#credentialsTable").on('click',"button[id^='del-']",  (e) => {
    var credentialId = e.target.id;
    console.log('credId' + credentialId);
    $.post( "/fisicHost/" + credentialId + "/credentials", data => {
    console.log(data);
    });
    });


    The post is being handled by this controller's method:



    @RestController
    public class Controlador {

    @Autowired
    private FisicHostDao fisicHostDao;
    @Autowired
    private CredentialDao credentialDao;

    @RequestMapping(value = "/fisicHost/{id}/credentials", method = RequestMethod.POST)
    public String deleteCredential(@PathVariable(value = "id") String credId){
    String parts = credId.split("-");
    int id = Integer.parseInt(parts[1]);
    Credential c = credentialDao.getCredentialById(id);
    credentialDao.delete(c);
    return "justreturnsomething";
    }

    }


    This is the Credential class:



    @Entity
    public class Credential {

    @Id
    private int id;

    @JsonIgnore
    @ManyToOne(fetch= FetchType.EAGER)
    private FisicHost fisicHost;

    private String user;
    private String password;
    private String notes;
    private String role;

    public Credential(){

    }

    public Credential(int id, FisicHost fisicHost, String user, String password, String notes, String role) {
    this.id = id;
    this.fisicHost = fisicHost;
    this.user = user;
    this.password = password;
    this.notes = notes;
    this.role = role;
    }

    public int getId() {
    return id;
    }

    public void setId(int id) {
    this.id = id;
    }

    public FisicHost getFisicHost() {
    return fisicHost;
    }

    public void setFisicHost(FisicHost fisicHost) {
    this.fisicHost = fisicHost;
    }

    public String getUser() {
    return user;
    }

    public void setUser(String user) {
    this.user = user;
    }

    public String getPassword() {
    return password;
    }

    public void setPassword(String password) {
    this.password = password;
    }

    public String getNotes() {
    return notes;
    }

    public void setNotes(String notes) {
    this.notes = notes;
    }

    public String getRole() {
    return role;
    }

    public void setRole(String role) {
    this.role = role;
    }
    }


    and this is the CredentialDao class:



    @Repository
    public class CredentialDaoImpl implements CredentialDao {



    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public List<Credential> getAllCredentialsByFisicHost(FisicHost fisicHost) {
    // Open a session
    Session session = sessionFactory.openSession();

    Criteria c = session.createCriteria(Credential.class).add(Restrictions.eq("fisicHost.id", fisicHost.getId()));

    List<Credential> allCredentials = c.list();

    // Close the session
    session.close();

    return allCredentials;
    }

    @Override
    public Credential getCredentialByUser(String user) {
    Session session = sessionFactory.openSession();
    Credential credential = session.get(Credential.class, user);
    session.close();
    return credential;
    }

    @Override
    public Credential getCredentialById(int id) {
    Session session = sessionFactory.openSession();
    Credential credential = session.get(Credential.class, id);
    session.close();
    return credential;
    }

    @Override
    public void save(Credential credential) {
    Session session = sessionFactory.openSession();
    session.save(credential);
    session.close();
    }

    @Override
    public void update(Credential credential) {
    Session session = sessionFactory.openSession();
    session.update(credential);
    session.close();
    }

    @Override
    @Transactional
    public void delete(Credential credential) {
    Session session = sessionFactory.openSession();
    session.delete(credential);
    session.close();
    }


    }



    Ok, so I'm debuggin the program and I see that when I get to these lines in the controller:



        Credential c = credentialDao.getCredentialById(id);
    credentialDao.delete(c);


    the credentials that are being loaded are the ones I want to, but the delete is not working ... the credential is not being erased from the DB.



    This is a picture of the debugger:



    enter image description here



    I can see that the credentialDao sessionFactory is = null .... this is a bit weird, might this be the problem ?? If so, why is this a problem if the sessionFactory is annotated as @AutoWired in the CredentialDaoImpl class !



    enter image description here










    share|improve this question

























      0












      0








      0







      No idea why this is not working !!



      I'm trying to delete a credential from my database but the delete method is not helping ...



      This is how I'm doing it:



      So this is triggering when the user clicks a button in the page:



      $("#credentialsTable").on('click',"button[id^='del-']",  (e) => {
      var credentialId = e.target.id;
      console.log('credId' + credentialId);
      $.post( "/fisicHost/" + credentialId + "/credentials", data => {
      console.log(data);
      });
      });


      The post is being handled by this controller's method:



      @RestController
      public class Controlador {

      @Autowired
      private FisicHostDao fisicHostDao;
      @Autowired
      private CredentialDao credentialDao;

      @RequestMapping(value = "/fisicHost/{id}/credentials", method = RequestMethod.POST)
      public String deleteCredential(@PathVariable(value = "id") String credId){
      String parts = credId.split("-");
      int id = Integer.parseInt(parts[1]);
      Credential c = credentialDao.getCredentialById(id);
      credentialDao.delete(c);
      return "justreturnsomething";
      }

      }


      This is the Credential class:



      @Entity
      public class Credential {

      @Id
      private int id;

      @JsonIgnore
      @ManyToOne(fetch= FetchType.EAGER)
      private FisicHost fisicHost;

      private String user;
      private String password;
      private String notes;
      private String role;

      public Credential(){

      }

      public Credential(int id, FisicHost fisicHost, String user, String password, String notes, String role) {
      this.id = id;
      this.fisicHost = fisicHost;
      this.user = user;
      this.password = password;
      this.notes = notes;
      this.role = role;
      }

      public int getId() {
      return id;
      }

      public void setId(int id) {
      this.id = id;
      }

      public FisicHost getFisicHost() {
      return fisicHost;
      }

      public void setFisicHost(FisicHost fisicHost) {
      this.fisicHost = fisicHost;
      }

      public String getUser() {
      return user;
      }

      public void setUser(String user) {
      this.user = user;
      }

      public String getPassword() {
      return password;
      }

      public void setPassword(String password) {
      this.password = password;
      }

      public String getNotes() {
      return notes;
      }

      public void setNotes(String notes) {
      this.notes = notes;
      }

      public String getRole() {
      return role;
      }

      public void setRole(String role) {
      this.role = role;
      }
      }


      and this is the CredentialDao class:



      @Repository
      public class CredentialDaoImpl implements CredentialDao {



      @Autowired
      private SessionFactory sessionFactory;

      @Override
      public List<Credential> getAllCredentialsByFisicHost(FisicHost fisicHost) {
      // Open a session
      Session session = sessionFactory.openSession();

      Criteria c = session.createCriteria(Credential.class).add(Restrictions.eq("fisicHost.id", fisicHost.getId()));

      List<Credential> allCredentials = c.list();

      // Close the session
      session.close();

      return allCredentials;
      }

      @Override
      public Credential getCredentialByUser(String user) {
      Session session = sessionFactory.openSession();
      Credential credential = session.get(Credential.class, user);
      session.close();
      return credential;
      }

      @Override
      public Credential getCredentialById(int id) {
      Session session = sessionFactory.openSession();
      Credential credential = session.get(Credential.class, id);
      session.close();
      return credential;
      }

      @Override
      public void save(Credential credential) {
      Session session = sessionFactory.openSession();
      session.save(credential);
      session.close();
      }

      @Override
      public void update(Credential credential) {
      Session session = sessionFactory.openSession();
      session.update(credential);
      session.close();
      }

      @Override
      @Transactional
      public void delete(Credential credential) {
      Session session = sessionFactory.openSession();
      session.delete(credential);
      session.close();
      }


      }



      Ok, so I'm debuggin the program and I see that when I get to these lines in the controller:



          Credential c = credentialDao.getCredentialById(id);
      credentialDao.delete(c);


      the credentials that are being loaded are the ones I want to, but the delete is not working ... the credential is not being erased from the DB.



      This is a picture of the debugger:



      enter image description here



      I can see that the credentialDao sessionFactory is = null .... this is a bit weird, might this be the problem ?? If so, why is this a problem if the sessionFactory is annotated as @AutoWired in the CredentialDaoImpl class !



      enter image description here










      share|improve this question













      No idea why this is not working !!



      I'm trying to delete a credential from my database but the delete method is not helping ...



      This is how I'm doing it:



      So this is triggering when the user clicks a button in the page:



      $("#credentialsTable").on('click',"button[id^='del-']",  (e) => {
      var credentialId = e.target.id;
      console.log('credId' + credentialId);
      $.post( "/fisicHost/" + credentialId + "/credentials", data => {
      console.log(data);
      });
      });


      The post is being handled by this controller's method:



      @RestController
      public class Controlador {

      @Autowired
      private FisicHostDao fisicHostDao;
      @Autowired
      private CredentialDao credentialDao;

      @RequestMapping(value = "/fisicHost/{id}/credentials", method = RequestMethod.POST)
      public String deleteCredential(@PathVariable(value = "id") String credId){
      String parts = credId.split("-");
      int id = Integer.parseInt(parts[1]);
      Credential c = credentialDao.getCredentialById(id);
      credentialDao.delete(c);
      return "justreturnsomething";
      }

      }


      This is the Credential class:



      @Entity
      public class Credential {

      @Id
      private int id;

      @JsonIgnore
      @ManyToOne(fetch= FetchType.EAGER)
      private FisicHost fisicHost;

      private String user;
      private String password;
      private String notes;
      private String role;

      public Credential(){

      }

      public Credential(int id, FisicHost fisicHost, String user, String password, String notes, String role) {
      this.id = id;
      this.fisicHost = fisicHost;
      this.user = user;
      this.password = password;
      this.notes = notes;
      this.role = role;
      }

      public int getId() {
      return id;
      }

      public void setId(int id) {
      this.id = id;
      }

      public FisicHost getFisicHost() {
      return fisicHost;
      }

      public void setFisicHost(FisicHost fisicHost) {
      this.fisicHost = fisicHost;
      }

      public String getUser() {
      return user;
      }

      public void setUser(String user) {
      this.user = user;
      }

      public String getPassword() {
      return password;
      }

      public void setPassword(String password) {
      this.password = password;
      }

      public String getNotes() {
      return notes;
      }

      public void setNotes(String notes) {
      this.notes = notes;
      }

      public String getRole() {
      return role;
      }

      public void setRole(String role) {
      this.role = role;
      }
      }


      and this is the CredentialDao class:



      @Repository
      public class CredentialDaoImpl implements CredentialDao {



      @Autowired
      private SessionFactory sessionFactory;

      @Override
      public List<Credential> getAllCredentialsByFisicHost(FisicHost fisicHost) {
      // Open a session
      Session session = sessionFactory.openSession();

      Criteria c = session.createCriteria(Credential.class).add(Restrictions.eq("fisicHost.id", fisicHost.getId()));

      List<Credential> allCredentials = c.list();

      // Close the session
      session.close();

      return allCredentials;
      }

      @Override
      public Credential getCredentialByUser(String user) {
      Session session = sessionFactory.openSession();
      Credential credential = session.get(Credential.class, user);
      session.close();
      return credential;
      }

      @Override
      public Credential getCredentialById(int id) {
      Session session = sessionFactory.openSession();
      Credential credential = session.get(Credential.class, id);
      session.close();
      return credential;
      }

      @Override
      public void save(Credential credential) {
      Session session = sessionFactory.openSession();
      session.save(credential);
      session.close();
      }

      @Override
      public void update(Credential credential) {
      Session session = sessionFactory.openSession();
      session.update(credential);
      session.close();
      }

      @Override
      @Transactional
      public void delete(Credential credential) {
      Session session = sessionFactory.openSession();
      session.delete(credential);
      session.close();
      }


      }



      Ok, so I'm debuggin the program and I see that when I get to these lines in the controller:



          Credential c = credentialDao.getCredentialById(id);
      credentialDao.delete(c);


      the credentials that are being loaded are the ones I want to, but the delete is not working ... the credential is not being erased from the DB.



      This is a picture of the debugger:



      enter image description here



      I can see that the credentialDao sessionFactory is = null .... this is a bit weird, might this be the problem ?? If so, why is this a problem if the sessionFactory is annotated as @AutoWired in the CredentialDaoImpl class !



      enter image description here







      java spring hibernate spring-mvc






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 21 '18 at 13:47









      Nacho Zve De La Torre

      17410




      17410
























          1 Answer
          1






          active

          oldest

          votes


















          0














          If your sessionFactory is null and you are using @Autowiered annotation, that's means the spring context are not recognizing your dependence.
          To resolve, create a factory function that returns a new SessionFactory and include then as a Bean using @Bean annotation. That garantee spring have the dependence in the context. Ex:



          @Bean
          public HibernateJpaSessionFactoryBean sessionFactory() {
          return new HibernateJpaSessionFactoryBean();
          }


          Then you can use @Autowired to instanteate your object.



          @Autowired
          private SessionFactory sessionFactory;


          Take a look on:
          https://stackoverflow.com/a/33881946/5192140.
          I think that mabe help you






          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53413511%2fhibernates-sessionfactory-not-deleting-an-object-from-db%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            If your sessionFactory is null and you are using @Autowiered annotation, that's means the spring context are not recognizing your dependence.
            To resolve, create a factory function that returns a new SessionFactory and include then as a Bean using @Bean annotation. That garantee spring have the dependence in the context. Ex:



            @Bean
            public HibernateJpaSessionFactoryBean sessionFactory() {
            return new HibernateJpaSessionFactoryBean();
            }


            Then you can use @Autowired to instanteate your object.



            @Autowired
            private SessionFactory sessionFactory;


            Take a look on:
            https://stackoverflow.com/a/33881946/5192140.
            I think that mabe help you






            share|improve this answer


























              0














              If your sessionFactory is null and you are using @Autowiered annotation, that's means the spring context are not recognizing your dependence.
              To resolve, create a factory function that returns a new SessionFactory and include then as a Bean using @Bean annotation. That garantee spring have the dependence in the context. Ex:



              @Bean
              public HibernateJpaSessionFactoryBean sessionFactory() {
              return new HibernateJpaSessionFactoryBean();
              }


              Then you can use @Autowired to instanteate your object.



              @Autowired
              private SessionFactory sessionFactory;


              Take a look on:
              https://stackoverflow.com/a/33881946/5192140.
              I think that mabe help you






              share|improve this answer
























                0












                0








                0






                If your sessionFactory is null and you are using @Autowiered annotation, that's means the spring context are not recognizing your dependence.
                To resolve, create a factory function that returns a new SessionFactory and include then as a Bean using @Bean annotation. That garantee spring have the dependence in the context. Ex:



                @Bean
                public HibernateJpaSessionFactoryBean sessionFactory() {
                return new HibernateJpaSessionFactoryBean();
                }


                Then you can use @Autowired to instanteate your object.



                @Autowired
                private SessionFactory sessionFactory;


                Take a look on:
                https://stackoverflow.com/a/33881946/5192140.
                I think that mabe help you






                share|improve this answer












                If your sessionFactory is null and you are using @Autowiered annotation, that's means the spring context are not recognizing your dependence.
                To resolve, create a factory function that returns a new SessionFactory and include then as a Bean using @Bean annotation. That garantee spring have the dependence in the context. Ex:



                @Bean
                public HibernateJpaSessionFactoryBean sessionFactory() {
                return new HibernateJpaSessionFactoryBean();
                }


                Then you can use @Autowired to instanteate your object.



                @Autowired
                private SessionFactory sessionFactory;


                Take a look on:
                https://stackoverflow.com/a/33881946/5192140.
                I think that mabe help you







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 21 '18 at 15:51









                Luno Batista

                32




                32






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53413511%2fhibernates-sessionfactory-not-deleting-an-object-from-db%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    404 Error Contact Form 7 ajax form submitting

                    How to know if a Active Directory user can login interactively

                    TypeError: fit_transform() missing 1 required positional argument: 'X'