Monday, February 27, 2012

EJBQL Delete Query Example

If you have worked with SEAM you may have used the method "entityManager.remove()" which is used to delete an entry from database. This method accepts one parameter, which is an entity.
(However the entity should be a managed one. Otherwise it throws an exception saying that you are trying to remove a detached object.)
You can use an EJBQL query to delete a record from database directly. In this case no managed entity is required. Following is an example query, which deletes one record from "Client" table.
It deletes the client whose clientId is 10.

DELETE FROM Client client where client.clientId = 10

Now I am going to use SEAM managed EntityManager to create a Query object as below and execute the query by calling it's "executeUpdate()" method.

Injecting EntityManager.
@In
EntityManager entityManager

Creating and executing query
Query q = entityManager.createQuery("DELETE FROM Client client where client.clientId                                       = 10");
q.executeUpdate();//delete row

6 comments: