views:

43

answers:

1

Hello!

I'm trying to implement my own Hibernate NamingStrategy based on the ImprovedNamingStrategy. This is quite nice... only the foreign keys of many-to-many relations are ugly.

Example scenario:

public class Teacher {
    @ManyToMany
    private Set<Course> courses;
}

public class Course {
    @ManyToMany
    private Set<Teacher> teachers;
}

With my custom naming stratgy

public class MyImprovedNamingStrategy extends ImprovedNamingStrategy {

    private static final long serialVersionUID = 1L;

    @Override
    public String foreignKeyColumnName(String propertyName, String propertyEntityName, String propertyTableName, String referencedColumnName) {
        String s = super.foreignKeyColumnName(propertyName, propertyEntityName, propertyTableName, referencedColumnName);
        return s.endsWith("_id") ? s : s + "_id";
    }
}

this would lead to a table teachers_courses with the columns teachers_id, courses_id.

What i try to realize is a table named teacher_course with the fields teacher_id, course_id. Any suggestions, how to sugularize my pluralized named properties of the entities?

Thanks in advance

+1  A: 

this would lead to a table teachers_courses (...)

Are you sure of this part? AFAIK, the default name of the JoinTable is made of The concatenated names of the two associated primary entity tables (owning side first), separated by an underscore (e.g. Teacher_Course).

(...) with the columns teachers_id, courses_id.

For this part, you'll have to implement a depluralizing algorithm that takes English spelling into account for:

Regular plurals

  • phases -> phase
  • kisses -> kiss (!)
  • dishes -> dish (!)
  • heroes -> hero
  • territories -> territory
  • days -> day

Almost regular plurals

  • leaves -> leaf
  • knives -> knife

Irregular plurals

  • sheep -> sheep
  • children -> child(!)
  • mice -> mouse
  • men - > man- women - > woman

Honestly, this doesn't look that easy and will probably require some kind of dictionary if you want to be correct.

I think a better option would be to override the default names using the JoinColumn and JoinTable annotations.

Pascal Thivent
@Pascal Thivent I agree
Arthur Ronald F D Garcia
Thats quite obvious. :( I'll use the @JoinTable and @JoinColumn Annotation for my @ManyToMany relations. Thanks!
Danny