Search code examples
javadatabasehibernatejpa

Is it possilbe to order many-to-many relation in JPA using a custom integer value stored in the join table?


I have two entities, Employer and Language, with a many-to-many relation between them. Each Employer can have multiple Language enitites, and they have a preferred order of the languages that they can speak. I want to store the preferred order in join table and retrieve it by ordered List<Language> but I am not sure how to implement it in JPA.

Here's an example of my Employer and Language entities:

@Entity
public class Employer {
    @Id
    private Long id;
    //.....
    @ManyToMany
    private List<Language> languages;
    //.....
}
@Entity
public class Language {
    @Id
    private Long id;
    //.....
}

This is how the database tables might look like:

employer table:
| id | bigint |
....

language table:
| id | bigint |
....

employer_language table:
| employer_id | bigint |
| language_id | bigint |
| order_index | int    |

Does JPA allow to do this?

I have considered to use a Map field that contains a Language as key and an order index by value but I think there could be a better solution.


Solution

  • Yes, it is possible. You have to use the @OrderColumn annotation. In your example, you would have something like this:

    @Entity
    public class Language {
        @Id
        private Long id;
        //.....
    }
    
    @Entity
    public class Employer {
        @Id
        private Long id;
        //.....
        @ManyToMany
        @OrderColumn(name = "order_index")
        private List<Language> languages;
        //.....
    }