Database independent string comparison with JPA

后端 未结 3 2013
攒了一身酷
攒了一身酷 2021-01-19 04:17

I\'m working with JPA (Hibernate as provider) and an underlying MySQL database.

I have a table containing every name of streets in Germany. Every streetname has a un

相关标签:
3条回答
  • 2021-01-19 04:47

    You also write a SQL query. It is like a normal query:

    Query sqlQuery = session.createSqlQuery("select * from CITY where name like binary :name').addString('name', name);
    

    Note that the code is roughly done.

    0 讨论(0)
  • 2021-01-19 05:01

    Seems like there is no way in configuring JPA to solve this problem. But what I found is, that it is possible to set the collation not only on the table-level, you can also set it for the whole database as discribed in the Reference Manual 12.1.10 CREATE DATABASE SYNTAX and 9.1.3.2. Database Character Set and Collation

    CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name
    [create_specification] ...
    
    create_specification:
        [DEFAULT] CHARACTER SET [=] charset_name
      | [DEFAULT] COLLATE [=] collation_name
    

    I only had to create the database with:

    CREATE DATABASE db_name CHARACTER SET latin1 COLLATE latin1_general_cs;
    

    With this, I could put a uniqueConstraint on the field name and insert both "Am kleinen Feld" and "Am Kleinen Feld" and when I query for one of them, I'll only receive one.

    However, thanks for the help

    0 讨论(0)
  • 2021-01-19 05:02

    To stay "independant" as you say for database and JPA provider i would avoid the getSingleResult() and fetch the list() and match in memory for the name. Probably you will get more than one but not 100 or more.

    Another way could be to save the name normalised (trimmed, to lower case) in a new field.

    0 讨论(0)
提交回复
热议问题