How to delete multiple rows in Hibernate

I tried to delete multiple rows from database using Hibernate. Its successfully done.

When I refresh the .jsp page, the deleted items will shown again.

Here's my code:

public int deleteUserById(String id[]) { SessionFactory sf = HibernateUtil.getSessionFactory(); int flag = 0; User user; try { for (int i = 0; i < id.length; i++) { Session session = sf.openSession(); session.beginTransaction(); Long Id = Long.parseLong(id[i]); user = new UserRepository().getUserByID(Id); session.delete(user); session.getTransaction().commit(); session.close(); } flag = 1; } catch (Exception e) { System.out.println("Error in deleteUserById=" + e); } return flag; }

Other Method:

public User getUserByID(Long Id) { SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); session.beginTransaction(); User user = null; try { user = (User) session.createQuery("from User where Id='" + Id + "'").list().get(0); } catch (Exception e) { System.out.println("Error in getUserByID=" + e); } session.close(); return user; }

Getting User method:

public ArrayList<User> getAllUser() { ArrayList<User> list_user = new ArrayList<User>(); SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); session.beginTransaction(); try { list_user = (ArrayList<User>) session.createQuery("from User").list(); } catch (Exception e) { System.out.println("Error in getAllUser=" + e); } session.close(); return list_user; }

I had used session.clear() but this doesn't solve the problem.


-------------Problems Reply------------

the user you fetch in getUserByID is queried in its own session which is closed and the user returned is detached. You should have one session per Request but you have nested sessions.

Try opening a session and a transaction at the beginning of the Request and commit the transaction at the end and eventually close the session.

if you really want to use a session of it's own for querying, then you have to merge the detached result :

user = session.merge(new UserRepository().getUserByID(Id));

Note : You are using many sessions and transactions in the for-loop in "deleteUserById" .... this is going to be rather resource consuming ... better open the session and transaction around that loop.

Category:java Views:4 Time:2018-12-06
Tags: java hibernate

Related post

  • How to delete multiple rows from datatable in VB.NET 2008? 2010-05-06

    How to delete multiple rows from datatable in VB.NET 2008 without looping? I do not want to delete from the database. I want to delete from the local data table. I know the Select method and also Remove and remove at method too. But that needs loopin

  • How to delete multiple rows from MYSQL table using PHP 2011-08-12

    I'm trying to learn php and ran into a problem. I'd appreciate any help. I have a database that looks like: ID USER AGE 1 name1 18 2 name2 19 3 name3 20 etc etc I want to delete multiple records. This is the code I am using for that: <?php $userna

  • How to delete multiple rows in table view? 2011-06-03

    Possible Duplicate: select multiple rows from uitableview and delete I am developing an application which requires the ability to select multiple rows and delete them. I placed the checkboxes in the rows to mark them for deletion. but every time, the

  • How to delete multiple rows in SQL Server 2009-10-18

    I have a secondhand sale car database and four tables with relationships. Same column names have relationships. Tables are: Record: RecID Markname Model... Features: FeatureID Featurename Marks: MarkID Markname Carfeature: CarfeatureID RecID FeatureI

  • Excel automation C#: How to delete multiple rows? 2010-08-23

    I have the following code and it does not delete the rows, it asks me to save over the current workbook but nothing is saved and EXCEL.EXE continues to run in Task Manager: protected void OpenExcelWorkbook(string fileName) { _app = new Excel.Applicat

  • How to delete multiple rows in a DataTable? 2010-05-26

    How can I delete specific DataRows within a loop of a DataTable rows which meet a custom condition -lets say the rows having an index of even number-? (Without using LINQ) Thanks --------------Solutions------------- It depends on what you mean by 'de

  • How to delete multiple rows based on a collection of non-primary key field items using LINQ-TO-SQL? 2009-07-10

    I have this columns, id int primary key, code int not null I want to delete all items where code equals to one of the items in a, IEnumerable<int> someEnumerable One possible way is using iteration. But I want to do it without explicit iteratio

  • SQL Server 2005: Deleting multiple rows with a single query 2010-07-17

    This should be a straightforward question, but I haven't found a clear answer yet. Does anyone know how to delete multiple rows from a single table in SQL Server 2005, using a single query? I wondered if it might just be the opposite of inserting mul

  • How to write a stored Procedure for deleting multiple rows in SQL Server 2005 2011-12-14

    Possible Duplicate: Parameterizing a SQL IN clause? I need to delete a multiple rows in a sql table from in a single click.How to write a stored procedure for this? but i should use "IN" keyword so that i can delete multiple rows at a

  • How to find and delete multiple rows 2013-01-31

    Hi, For an Excel spreadsheet I am hoping to get help with code that will delete multiple rows as follows: In Column A Find cell = "Total" Delete that row and the following two rows Repete until there are no more "Total" in ColumnA I will be adding th

  • Deleting Multiple Rows with Zend DB Table Problem 2010-04-08

    I have this data in my db Col1 Col2 DA Data1 DA Data2 DA Data3 DA Data4 DA Data5 I would like to delete all the values WHERE col1 = DA using my Zend DB Table adapter. The code below does not seem to work for multiple rows public function delete($key)

  • Deleting Multiple rows from a TableView 2010-05-31

    Possible Duplicate: iPhone: modifying view when user shakes hi Frnz, i want to delete multiple rows from a table view based on users selection.obviously i cant use didSelectRowAtIndexPath method coz it will be called for every row selected. i want to

  • UITableView: can I delete multiple rows? 2010-06-01

    I want to delete multiple rows from a table view, based on the user's selection. Obviously I can't use the didSelectRowAtIndexPath method because it will be called for every row selected. I want to allow the user to select multiple rows for deletion

  • Edit & delete multiple rows in UITableView simultaneously 2011-06-03

    In my app I need to delete multiple rows in a table, edit the table and get a check box beside the table. When checked then the table cells are deleted. It is like the iPhone message app. How can I do this, please help me. --------------Solutions----

  • Delete multiple rows with checkbox form DB table 2011-06-17

    here is my code - <?php $host="localhost"; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name="test"; // Database name $tbl_name="test_mysql"; // Table name // Connect to server and select databse. mysql_connect(

  • Delete multiple rows from Grid 2011-07-20

    How do I delete multiple rows from XtraGrid ? I am using DevEx version 10.2. Any tutorials available ? --------------Solutions------------- You can get the selected rows using the GetSelectedRows method (nicely named right?). Then you can just use a

  • PHP/MySQL isolating database access in a class - how to handle multiple row result set in an OOP manner 2009-08-27

    PHP/MySQLisolating database access in class - how to handle multiple row Selects Here’s a coding question. I isolated all DB access functions in a class <?php class DB { var $conn; function DBClass () { @$this-> conn = mysqli_connect (DB_SERVER

  • How to delete all rows from all tables in a SQL Server database? 2009-12-14

    How to delete all rows from all tables in a SQL Server database? --------------Solutions------------- Note that TRUNCATE won't work if you have any referential integrity set. In that case, this will work: EXEC sp_MSForEachTable 'DISABLE TRIGGER ALL O

  • How to retrieve multiple rows from a stored procedure with Linq to SQL? 2009-12-27

    I've recently started to work with Linq to SQL and wondered how to get multiple rows as a result of executing a stored procedure,here's a simple sp i want to work with: CREATE PROCEDURE gsp_ftsmultiple @SearchKey varchar(100) AS BEGIN SET NOCOUNT ON;

  • How to have multiple rows of items on a UIToolbar? 2010-03-02

    I'm trying for what is done in Apple's "Maps" app when "Directions" is selected: Does anyone know how to have multiple rows of UIBarButtonItems? I haven't found the answer anywhere. I can add items in a single row to the UIToolbar as follows: NSArray

  • How to delete a row in TableLayout dynamically 2010-10-11

    I am having a TableLayout for which I added rows dynamically.In each of the row there are 2 elements of which one is TextView other is Button.When I click the button that is present in a row,that row should be deleted.How can this be done in Android

  • Efficient way to delete multiple rows in HBase 2011-01-06

    Is there an efficient way to delete multiple rows in HBase or does my use case smell like not suitable for HBase? There is a table say 'chart', which contains items that are in charts. Row keys are in the following format: chart|date_reversed|ranked_

  • delete multiple rows in datagridview 2011-08-01

    I have a function to delete single rows on right click delete in a datagridview.. code: private void dataGridView1_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { var hti = dataGridView1.HitTest(e.X, e.Y); if (hti.R

  • How to retreive multiple rows from stored procedure in mysql? 2011-11-29

    Am trying to fetch out a field through stored procedure and i used following query. I aimed at fetching out multiple rows, but it executes the result successfully only when a single row exists. Or else it returns an error as i mentioned below. MYSQL

  • Better method to delete multiple rows in a myql database with PHP? 2011-12-17

    Let's say I have an array with a bunch of ids for a mysql table: $idList = array('1','2','3','4','5'); I want to delete the rows associated with each id. Which method is more preferable/better/faster (IYO)? $idListString = implode(",",$idList); mysql

Copyright (C), All Rights Reserved.

processed in 0.151 (s). 11 q(s)