我正在使用带有Hibernate的Spring JPA Repository进入MySQL数据库。在那个环境中,我有以下实体:
@Entity
@Table(name="cod__postales")
public class CodigoPostal {
@Id
@GeneratedValue
private Long registro;
@Column(name = "`POST_Nº_CODIGO`", length = 6, nullable = false)
private String codigo = " ";
@Column(name = "POST_DESCRIP", length = 30, nullable = false)
private String descripcion = " ";
@Column(name = "POST_ZONA_ASIG", length = 2, nullable = false)
private String zona = " ";
此外,我还有以下Spring JPA存储库:
public interface CodigoPostalRepository extends JpaRepository<CodigoPostal, Long> {
CodigoPostal findOneByCodigo(String codigo);
}
如您所见,第一列名称'º'上有一个特殊字符。问题在于,当我调用 repo.findOneByCodigo()方法时,会生成以下SQL
select codigopost0_.registro as registro1_2_,
codigopost0_.`post_nº_codigo` as post_nº_2_2_,
codigopost0_.post_descrip as post_des3_2_,
codigopost0_.post_zona_asig as post_zon4_2_
from cod__postales codigopost0_
where codigopost0_.`post_nº_codigo`=?
问题是sql因为名称spring / hibernate对该列的分配而产生错误: aspost_nº_2_2_。
我该如何避免这种情况?
答案 0 :(得分:1)
这是关于此查询的第一个想法,我的建议是引入一个原生查询,它可以帮助您将'更改为post_nº_2_2_。'更改为:' as post_n_2_2 _。< /强>”。
示例:强>
@Query(value = " select codigopost0_.registro as registro1_2_,
codigopost0_.`post_nº_codigo` as post_n_2_2_,
codigopost0_.post_descrip as post_des3_2_,
codigopost0_.post_zona_asig as post_zon4_2_
from cod__postales codigopost0_
where codigopost0_.`post_nº_codigo`=?", nativeQuery = true)
public interface CodigoPostalRepository extends JpaRepository<CodigoPostal, Long> {
CodigoPostal findOneByCodigo(String codigo);
}
有关此link的更多信息。
答案 1 :(得分:0)
最后我通过将characterEncoding参数添加到url字符串来解决这个问题:
spring.datasource.url=jdbc:mysql://localhost/madr?characterEncoding=UTF-8
无论如何,我已经向Hibernate打开了一个问题,因为对于每个人来说这可能不是一个有效的选项https://hibernate.atlassian.net/browse/HHH-10493
答案 2 :(得分:-1)
更改
@Column(name = "`POST_Nº_CODIGO`", length = 6, nullable = false)
到
@Column(name = "`POST_N_CODIGO`", length = 6, nullable = false)