Well, I do not understand why me code does not work. Could Someone please take a look. It does not provide any error messages but the Customer will not be deleted. Other methods are working well (getCustomerbyId, getAllCustomers and so)
Thanks
public void deleteCustomerById(long id) {
EntityManager em = null;
try {
em = JpaUtil.getFactory().createEntityManager();
em.getTransaction().begin();
Query query = em.createQuery("Delete from Customer c where c.id = :id");
query.setParameter("id", id);
em.getTransaction().commit();
} finally {
JpaUtil.closeQuietly(em);
}
}
You need to execute queries to have SQL issues to the database; in this case you will want to use executeUpdate() and get the modified row count to verify something was deleted or not.
em.getTransaction().begin();
Query query = em.createQuery("Delete from Customer c where c.id = :id");
query.setParameter("id", id);
int rows = query.executeUpdate();
em.getTransaction().commit();
You are creating a query but not executing it.
You should add
query.executeUpdate();
before committing
Use jpa APis find(Customer.class) to find the customer object then use romove(object)
Related
I am insert data in db is good. The problem is after inserted data i am trying to get last inserted data primary key column. But i can't how to solve this problem.
note : i am using jpql , Thanks
public void insertData(String hcpHceId) {
EntityManager em = getEntityManager();
em.getTransaction().begin();
// Query query = em.createNativeQuery("INSERT INTO mdm_id (hcp_hce_id) VALUES(:id)" );
Query query = em.createNativeQuery("INSERT INTO mdm_id (hcp_hce_id) VALUES(?)");
query.setParameter(1, hcpHceId);
query.executeUpdate(); // Successfully inserted data
List list = query.setMaxResults(1).getResultList(); // Error line
em.getTransaction().commit();
} catch (Exception error) {
error.printStackTrace();
logger.error(error.getMessage());
} finally {
em.close();;
}
}
You are trying to retrieve the list from the same execute query. Query is an immutable object. You must create a new query with the proper select statement, so you will be able to retrieve data from database.
After the executeUpdate, create the new query using, v.g. (as you did not show your entity graph, using native sql):
Query retQuery = em.createNativeQuery("SELECT hcp_hce_id FROM mdm_id LIMIT 1");
String id = (String) retQuery.getSingleResult();
assert(id == hcpHceId);
I need to store the laboratory points for a certain student, the first Select works good but when i try to update the new value for lab_points with WHERE clause the program crash. When i skip the WHERE the program run fine but all values are changed.
What will be the problem for UPDATE?
EntityManagerFactory emf = (EntityManagerFactory)getServletContext().getAttribute("emf");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
EntityManager updateEm = emf.createEntityManager();
String nume, prenume;
int lab_points;
for(List<String> linie: linesAsList)
if(linie.get(1).matches("[a-zA-Z- ]+") && linie.get(2).length()>=2) {
nume = linie.get(1).split(" ")[0];
prenume = linie.get(1).split(" ")[1];
lab_points = (Integer) em.createQuery("select n.lab_points from Record as n where n.student.nume=:nume and n.student.prenume=:prenume and n.student.grupa=:grupa and n.cours.numeCurs=:curs")
.setParameter("nume", nume).setParameter("prenume", prenume)
.setParameter("grupa",linie.get(2)).setParameter("curs","Programare avansata").getSingleResult();
lab_points = lab_points + Integer.parseInt(linie.get(3).trim());
System.out.println(lab_points);
updateEm.getTransaction().begin();
updateEm.createQuery("update Record as n set n.lab_points=:points where n.student.nume=:nume").setParameter("nume",nume)
.setParameter("points",lab_points)
.executeUpdate();
updateEm.getTransaction().commit();
System.out.println(em.createQuery("select n.lab_points from Record as n where n.student.nume=:nume and n.student.prenume=:prenume and n.student.grupa=:grupa and n.cours.numeCurs=:curs")
.setParameter("nume", nume).setParameter("prenume", prenume)
.setParameter("grupa", linie.get(2)).setParameter("curs", "Programare avansata").getSingleResult());
}
if (updateEm.getTransaction().isActive())
updateEm.getTransaction().rollback();
updateEm.close();
if (em.getTransaction().isActive())
em.getTransaction().rollback();
em.close();
And this my database error message: error
JPQL doesn't allow statement like
n.student.nume
in an UPDATE statement, because it will try to translate to a SQL JOIN which it's not allowed in an UPDATE statement. Unfortunately JPQL doesn't support subqueries in UPDATE statements.
So the only solution it's to map the student_id to a property in Record entity
#Column(name = "student_id", insertable=false, updatable=false)
private Long authorId;
And to split the task into two queries like this:
List<Long> ids = em.createQuery("SELECT s.id FROM Student s WHERE s.nume = :nume", Long.class)
.setParameter("nume", nume)
.getResultList();
em.createQuery("UPDATE Record r SET r.lab_points = :points WHERE b.student_id IN :ids")
.setParameter("ids", ids)
.setParameter("points",lab_points)
.executeUpdate();
I'm trying to delete the objects in the database.
My first attempt was:
public void removeAll(){
TypedQuery<anObject> query = em.createQuery(
"DELETE FROM tablName",
anObject.class);
query.executeUpdate();
}
this gave me an exception so I had a look at the example on the objected site and updated my code to resemble theirs:
public int removeAll(){
int deleted = em.createQuery(
"DELETE FROM tableName").executeUpdate();
}
I'm getting the same exception:
com.objectdb.o._TransactionRequiredException: Attempt to run update query when no transaction is active
anyone know what I can do to solve?
I've added an answer here just in case someone else stumbles across this and it might help.
I had forgotten to add #Transactional notation.
The final code snippet looks like:
#Transactional
public void removeAll(){
TypedQuery<anObject> query = em.createQuery(
"DELETE FROM tableName",
anObject.class);
query.executeUpdate();
}
I have the following query in Hibernate.I got Hibernate Exception and I don't understand why Hibernate throws this exception. Could anyone help me?
Session session = this.sessionFactory.openSession();
session.createQuery("delete from Laboratory l where l.id=:laboratoryId")
.setParameter("laboratoryId", laboratoryId).executeUpdate();
session.close();
Try to add some spaces between the = sign and the bind name :laboratoryId and remove the alias:
Session session = this.sessionFactory.openSession();
session.createQuery("delete from Laboratory where id = :laboratoryId")
.setParameter("laboratoryId", laboratoryId)
.executeUpdate();
session.close();
Are you sure that laboratoryID has value? For my query builder I used something like this:
if (!laboratoryId.isEmpty()) {
query.setParameter("laboratoryId", laboratoryId());
}
also same thing for query
"delete o from Laboratory o"
if(!laboratoryId.isEmpty()){
query.append("where o.id = (:laboratoryId)")
}
But I used it for String values
Please show code for laboratoryId - is it user input or what?
You can try this one.
DELETE Clause
The DELETE clause can be used to delete one or more objects. Following is the simple syntax of using DELETE clause:
String hql = "DELETE FROM Employee " +
"WHERE id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("employee_id", 10);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);
I got this simple Hibernate query set up but it returns nothing, here is my code:
EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("timereg");
EntityManager em = emf.createEntityManager();
int id = em.createQuery("SELECT emp.id FROM Employee as emp WHERE emp.bsn = '398723916'").getFirstResult();
object.getEmployee().setId(id);
System.out.println("query returns employee id: " + id);
The stupid thing is that id stays zero but when i execute this query in PostgreSQL it returns 37.
I think hibernate does not like my way of implementing a select query, does anyone know what is wrong with my select query ?
THE ANSWER:
There was nothing wrong with the select query i just had to use getSingeResult() instead of getFirstResult();
Change the code into:
EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("timereg");
EntityManager em = emf.createEntityManager();
Object ob = em.createQuery("select id from Employee where bsn = '398723917'").getSingleResult();
object.getEmployee().setId(Integer.parseInt(ob.toString()));
System.out.println(ob);
This is the total solution for my problem, but i got inspired by Yanflea so he deserves all the credits.
You are using the method getFirstResult(), which gives you the position of the record in the table. You should use getSingleResult() instead. See http://docs.oracle.com/javaee/6/api/javax/persistence/Query.html.
EDIT
Here it is :
Object ob = em.createQuery("select id from Employee where bsn = '398723917'").getSingleResult();