Dyip302 Dyip302 - 13 days ago 14
Java Question

JPA Hibernate is creating temporary tables for a simple update query

I have a simple query in my repository to increment number of comments for a post given the post object:

public interface PostsRepository extends PagingAndSortingRepository<Post, Long>{

//...

@Modifying
@Query("UPDATE Post p set p.numComments = p.numComments + 1 where p = :post")
void incrementNumComments(@Param("post") post obj);

//...
}


Model:

@Entity
@Table(name="posts")
@Inheritance(strategy= InheritanceType.JOINED)
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "post_id", updatable = false, nullable = false)
@Access(AccessType.PROPERTY)
private Long id;
}


However, hibernate seems to be using a temporary table to execute the query. Here are the generated queries from the logs:

Hibernate: insert into HT_posts select pos0_.post_id as post_id from posts pos0_ where pos0_.s_id=?
Hibernate: update posts set num_comments=num_comments+1 where (post_id) IN (select post_id from HT_posts)


Is there a way to prevent Hibernate from using temporary tables for this query?

Thanks

Answer

You can find details about Multitable bulk operations.

As @Giovanni mentioned, this is because of the use of InheritanceType.JOINED.