简体   繁体   中英

Does JPA load entities in JPQL, as it does when using entities in code?

I have a two tables: Person and House , the mapping is one to one.

Now I have to assign the address of Person and House (which can be different) to the same address.

There are more than 5000 records. Which will be faster? Using Code to update the entities one by one, eg

for (id : Ids) {
    Person person = PersonDAO.find(id);
    person.setAddress ("abc");
}

and then doing same with House ;

Or should I use JPQL to update both in two different queries, eg

UPDATE Person p SET p.Address = "abc" WHERE ID IN(.....ID QUERY)

My question is what will be faster? Will the update using JPQL have the same performance, same as that in code? Or should I use native query to NOT load the entities, as I only want performance.

Using the query will be faster (and much more memory efficient), as the query provider will translate the JPQL query to native SQL. Also, if you use entities directly, the number of queries made against the database will be siginificantly higher (one select and update for each and every row).

The native query will be faster, as it doesn't have to translate anything.

If you want it to be even faster, you can use a PreparedStatement . With the .addBatch() method you add the query to the batch, and with the executeBatch() method you will execute the full batch, minimizing the amount of times being switched between user and kernel mode.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM