-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 
Author Message
 Post subject: How to delete an entity by the auto-generated ID in MySQL
PostPosted: Mon Mar 06, 2017 6:12 am 
Newbie

Joined: Mon Mar 06, 2017 6:06 am
Posts: 3
I want to get the auto-generated ID of already inserted entity to MySQL , I have an application made in javafx with hibernate , and I can't delete entity because the ID is autogenerated and I have to get the id of entity , so after I save it to database , then write the username and password I want it to give me the Id of inserted username and password I write in the fields. So..I write in fields the username and password and then click a delete button and it should return me the id of the pas and username inserted and then delete the entity from database.

Or..how can I delete an entity by auto generated ID? Because if I just try the normal way it gives me this in the console and doesen't delete the entity so I want to delete it by that auto generated ID:
Mar 06, 2017 12:10:23 PM org.hibernate.event.internal.DefaultDeleteEventListener deleteTransientEntity
INFO: HHH000114: Handling transient entity in delete processing

This is the main class :

Code:
public class TestMain extends Application {
     static Employee m = new Employee();

    public static void main(String[] args)  {  launch(args);   } 

        @Override
        public void start(Stage primaryStage) throws Exception {
            // TODO Auto-generated method stub

                Stage window = primaryStage;

                window.setTitle("WELCOME");

                Label l1 = new Label();
                // l1.setFont(new Font(48));
                l1.setText("SMS");
                l1.setTranslateY(-180);                           

                Button closeBut = new Button("Exit.");
                closeBut.setTooltip(new Tooltip("Click to exit application"));
                closeBut.setOnAction(e -> window.close());
                Button save = new Button ("Save");
                save.setTooltip(new Tooltip("Click to save to database"));


                Label l2 = new Label("Username ");
                TextField username = new TextField();
                username.setTooltip(new Tooltip("Enter your new username"));
                username.setPromptText("username");
                GridPane.setConstraints(l2,0,0);
                GridPane.setConstraints(username,1,0);

                Label l3 = new Label("Password ");
                PasswordField password = new PasswordField();
                password.setTooltip(new Tooltip("Enter your new password"));
                password.setPromptText("password");
                GridPane.setConstraints(l3,0,1);
                GridPane.setConstraints(password,1,1);

                Label l4 = new Label();
                GridPane.setConstraints(l4,0,4);
                GridPane.setConstraints(save,0,2);
                GridPane.setConstraints(closeBut,1,2);             

                //Configureation Hibernate
               // Configuration config = new Configuration();
                //config.configure("hibernate.cfg.xml");

                   SessionFactory sf = new Configuration().configure().buildSessionFactory();

                 // 
                       save.setOnAction(e -> {
                       m.setUser(username.getText());
                       m.setPassword(password.getText());   

                       Session session = sf.openSession();   
                       session.beginTransaction();                                                                                       
                       session.delete(m);                     
                       session.getTransaction().commit();

                });

                GridPane grid = new GridPane();
                grid.setPadding(new Insets(10,10,10,10));
                grid.setVgap(8);
                grid.setHgap(0);

                grid.getChildren().addAll(l1,l2,username,l3,password,save,l4,closeBut);
                grid.setAlignment(Pos.CENTER);
                Scene scene = new Scene(grid,300,400);
                window.setScene(scene);
                window.show();

   }
}               


And this is the Employee class :

Code:
package mypackage;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.*;
import javax.persistence.Id;

@Entity(name="EMPLOYEE")
public class Employee {

    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="ID")
    private int Id;


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

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


    public int getId() {
        return Id;
    }

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

    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;
    }
    }


Top
 Profile  
 
 Post subject: Re: I want to delete an entity by the autogenerated ID.
PostPosted: Mon Mar 06, 2017 7:59 am 
Hibernate Team
Hibernate Team

Joined: Thu Sep 11, 2014 2:50 am
Posts: 1628
Location: Romania
Quote:
so after I save it to database


Why do you call delete on the save handler? You should call persist which will properly assign the entity identifier.

Code:
save.setOnAction(e -> {
    m.setUser(username.getText());
    m.setPassword(password.getText());   

    Session session = sf.openSession();   
    session.beginTransaction();                                                                                       
    session.delete(m);                     
    session.getTransaction().commit();
});


Also, there all other issues like:

1. You never seem to call session.close, so resources will leak.
2. You should call commit in a try block, where the catch block does the rollback, and the finally block closes the Session. Something like this.


Top
 Profile  
 
 Post subject: Re: How to delete an entity by the auto-generated ID in MySQL
PostPosted: Mon Mar 06, 2017 12:43 pm 
Newbie

Joined: Mon Mar 06, 2017 6:06 am
Posts: 3
Because I didn't make a delete button yet, just changing to save/delete when needed to save or delete. I wanted to make it work before making the button , this is not important i`ll make that button.


When I use the persist method it says : Cannot make a static reference to the non-static method persist(Object) from the type EntityManager.


Top
 Profile  
 
 Post subject: Re: How to delete an entity by the auto-generated ID in MySQL
PostPosted: Mon Mar 06, 2017 1:28 pm 
Hibernate Team
Hibernate Team

Joined: Thu Sep 11, 2014 2:50 am
Posts: 1628
Location: Romania
That sounds like a compilation error to me.


Top
 Profile  
 
 Post subject: Re: How to delete an entity by the auto-generated ID in MySQL
PostPosted: Mon Mar 06, 2017 2:47 pm 
Newbie

Joined: Mon Mar 06, 2017 6:06 am
Posts: 3
I made it. Created a query.

Code:
  delete.setOnAction(e ->{
                        
                        Session session = sf.openSession();   
                        Transaction tx = null;                
                             tx = session.beginTransaction();
                        Query query = session.createQuery("from EMPLOYEE where user = :user and password = :password");
                             query.setParameter("user", username.getText());
                             query.setParameter("password", password.getText());
                             
                             Employee userToDelete= (Employee)query.uniqueResult(); 

                             session.delete(userToDelete);     
                               tx.commit();                        
                                session.close();
                                                                                                                                                                      
                     });


Now the program works and it delets the entity by it's ID after I write username and password. Posted the solution , maybe someone needs it like I did.


Top
 Profile  
 
 Post subject: Re: How to delete an entity by the auto-generated ID in MySQL
PostPosted: Mon Mar 06, 2017 3:17 pm 
Hibernate Team
Hibernate Team

Joined: Thu Sep 11, 2014 2:50 am
Posts: 1628
Location: Romania
Don't forget about:

Quote:
Also, there all other issues like:

1. You never seem to call session.close, so resources will leak.
2. You should call commit in a try block, where the catch block does the rollback, and the finally block closes the Session. Something like this.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.