Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an index on join tables using Hibernate annotations?

Tags:

java

hibernate

I have a relationship as follows using Hibernate annotations, this is what I tried:

public class Job{

...

@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "jobs_resource_locations")
@ForeignKey(name = "job_inputs_fk")
@Index(name="job_inputs_fk")
private List<FileSystemLocation> inputs;

This sort of thing works nicely on ManyToOne like so:

@ManyToOne
@JoinColumn(name = "service_call_id", referencedColumnName = "id")
@ForeignKey(name = "job_service_call_fk")
@Index(name = "job_service_call_fk")
private ServiceCall serviceCall;

I wanted to ensure that the foreign key gets indexed on PostgreSQL and that the schema looks similar on MySQL, hence the @ForeignKey and @Index with the same name (MySQL always creates an index with the same name as the FK).

I cannot create the index on the inverse side because FileSystemLocation is unaware of the relationship. Hence the JoinTable.

The former example fails since Hibernate finds no column in Job to index:

org.hibernate.MappingException: Unable to find logical column name from physical name null in table jobs

Does anyone know how to create indices on JoinTable foreign keys using Hibernate?

like image 638
Sindri Traustason Avatar asked Dec 09 '10 15:12

Sindri Traustason


People also ask

What is @basic annotation in Hibernate?

We can use the @Basic annotation to mark a basic type property: @Entity public class Course { @Basic @Id private int id; @Basic private String name; ... } In other words, the @Basic annotation on a field or a property signifies that it's a basic type and Hibernate should use the standard mapping for its persistence.

What is the use of @entity annotation in Hibernate?

@Entity annotation marks this class as an entity. @Table annotation specifies the table name where data of this entity is to be persisted. If you don't use @Table annotation, hibernate will use the class name as the table name by default. @Id annotation marks the identifier for this entity.

Does Hibernate use index?

By default, Hibernate Search will use the fully qualified class name as the index name. With the @Entity annotation from JPA, we map a class to a database table and, its fields to the table columns.

What is index in Hibernate?

Indexing. The short answer is that indexing is automatic: Hibernate Search will transparently index every entity each time it's persisted, updated or removed through Hibernate ORM. Its mission is to keep the index and your database in sync, allowing you to forget about this problem.


1 Answers

It's not exactly the answer you would like to receive, but this is the expected behavior. In other words: this is not supported. See the following JIRA for more details:

https://hibernate.atlassian.net/browse/HHH-4263

like image 88
jpkrohling Avatar answered Sep 19 '22 14:09

jpkrohling