Can I update multiple columns of table by query language using JPA - java

I created one table like student and I fetched the address based on age (like age = 22). Now I want to update the address based on age "22" to all address columns of table. How can I do this?
Below is my code:
public static void main(String[] args) {
EntityManager entityManager = Persistence.createEntityManagerFactory(
"demoJPA").createEntityManager();
Query query = entityManager.createQuery("SELECT student FROM Student student WHERE student.age = 22");
System.out.println("Data is" + query.getResultList().size());
List<Simpletable> simpletable = query.getResultList();
for (Simpletable simpletable1 : simpletable){
System.out.println(simpletable1.getAddress());
}
}
I fetched data but how can I update now. Is it possible to iterate through a loop and setAddress("US")

Since you are creating a standalone application, you must open a transaction first, then you can simply change the field values in your object and when the transaction is committed, the changes get flushed to the database automatically.
EntityTransaction tx = entityManager.getTransaction();
try {
tx.begin();
try {
for(SimpleTable simpleTable : simpleTables){
simplaTable.setAddress(newAddress);
}
} finally {
tx.commit();
}
} catch (Exception e) {
// handle exceptions from transaction methods
}
--Edit--
An alternative to edit all records without having to first fetch them is to do a bulk update, still within a transaction, like this:
entityManager.createQuery("UPDATE SimpleTable s " +
"SET s.address.state = ?1 " +
"WHERE s.address.country = ?2")
.setParameter(1, "FL")
.setParameter(2, "US")
.executeUpdate();

Related

javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Can not issue data manipulation statements with executeQuery()

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

Hibernate (HQL) select query with list of ids as parameter

I have to requirement to fetch product information from the product table by product_code.
so, I have to pass a list of product_code to my select query with the help of WHERE Clause IN.
Am able to pass list of product_code but its returning only one product information ( select query giving results for the first product_code).
Please find my code below that am having issue.
public JSONArray getUpdatedProductDescription(List<String> product_code_list)
{
Collection<String> produceCollection=product_code_list;
List<String> code = null;
Configuration cfg=new Configuration();
cfg.configure("Hibernate.cfg.xml");
SessionFactory factory=cfg.buildSessionFactory();
Session session=factory.openSession();
Transaction t=session.beginTransaction();
String hql = "from Product where code in(:code)";
Query query = session.createQuery(hql);
query.setParameterList("code", produceCollection);
List<Product> listProducts = query.list();
for(Product prod : listProducts)
{
System.out.println("Product Details:::"+prod.getCode());
}
}

How to return Primary Key from Insert statement Mysql Java Eclipselink

I have a simple namednativequery that generates new PK upon insert for REST web service.
Message.java
#NamedNativeQueries({#NamedNativeQuery( name="Message.send", query="INSERT INTO Leaf.Message (MessageID,Status,Message,Description,SentTime,ipAdd) VALUES\n" +
"(null,?Status,?Message,NOW()),?ipAdd;")})
AbstractFacade.java
public void CreateMessage(Message entity, InetAddress clientIP) {
try{
javax.persistence.Query q = getEntityManager().createNamedQuery("Message.send",entityClass);
q.setParameter("Status", "send");
q.setParameter("Message", entity.getMessage());
q.setParameter("ipAdd",clientIP.hashCode());
q.executeUpdate();
}
catch(Exception e){
String s= ""+e.getMessage().toString();
}}
How do I get the newly created PK? Is it using SELECT LAST_INSERT_ID() ? Because the executeUpdate doesn't return the result? and ResultSet rs = q.getGeneratedKeys(); is not a valid syntax for this.
Yes, for MySQL, it would be LAST_INSERT_ID.
However, in your case it would make much more sense to just use EntityManager::persist. For example, have a look at the Hibernate tutorial:
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist( new Event( "Our very first event!", new Date() ) );
entityManager.persist( new Event( "A follow up event", new Date() ) );
entityManager.getTransaction().commit();
entityManager.close();
In your case, you would pass an instance of Message to the persist method.
After persist has returned, you can directly access the identity of the entity by calling getMessageID:
getEntityManager().persist(message);
System.out.println("Inserted message: " + message.getMessageID());

JPA Delete query not working

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)

Hibernate Exception - could not locate named parameter [:laboratoryId]

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

Categories

Resources