February 23rd, 2023

Queries

If you need to do the mass updates of all the rows, then in case of JPA, you need to get the row and update and again get the row and update, whereas in the case of Native query, all the rows can be updated with a single query

Types of queries:

1. JPQL – queries using entities. This works per record.

				
					TypedQuery<Course> query = em.createQuery("select c from Course c", Course.class);
				
			

2. Native queries – Same as sql query. This is helpful if query in all records are required.

				
					Query query = em.createNativeQuery("select * from course", Course.class);
				
			

@Transactional

@Transactional – To save the changes in the database in case of insert and update. This also enables to store all the transactions in the PersistenceContext 

If a method is having multiple transactions and if any of the method fails, all the other transactions roll back to it’s previous state.

Changes are sent to the database only at the end of all the transactions.

In Hibernate terminology, Session = PersistenceContext

@Transactional should be present in either the Repository or at the Test method.

				
						@Transactional
	void someTest() {
		Student student = em.find(Student.class, 20001L);
		Passport passport = student.getPassport();
		passport.setNumber("E12345-0");
		student.setName("Ranga - updated");
	}
				
			

Hibernate Basics