【问题标题】:CrudRepository wrong select query [closed]CrudRepository 错误的选择查询 [关闭]
【发布时间】:2016-01-02 16:22:39
【问题描述】:

我有以下模型类

@Entity
@Table(name = "tests")
public class Test implements Serializable {

@Column(nullable = false)
private String prop1;

@Column(nullable = false)
private String prop2;

@Id
@Column(nullable = false)
private String prop3;

@Column(nullable = false)
private String prop4;

public Test(final String prop1, final String prop2, final String prop3, final String prop4) {
    this.prop1 = prop1;
    this.prop2 = prop2;
    this.prop3 = prop3;
    this.prop4 = prop4;
}

我创建了以下扩展CrudRepository的接口

public interface TestRepository extends CrudRepository<Test, String> {
    // blank
}

在我的控制器中,我有以下代码:

@Controller
@RequestMapping("/test")
public class TestController {

@Autowired
private TestRepository testRepository;

@RequestMapping(method = GET)
@ResponseBody
public Iterable<Test> fetchTests() {
    return testRepository.findAll();
}

问题在于,当运行fetchTests 方法时,生成的查询类似于:

select test0_.prop1 as prop11_0_, test0_.prop2 as prop22_0_, test0_.prop3 as prop33_0_, test0_.prop4 as prop44_0_ from tests test0_

应该只是

select tests.prop1 as prop11_0_, tests.prop2 as prop22_0_, tests.prop3 as prop33_0_, tests.prop4 as prop44_0_ from tests

我不明白额外的tests0_ 引用来自哪里?关于什么是错的任何想法?我正在使用 postgre 作为 dbms。

【问题讨论】:

  • "test0_" 是表“tests”的别名。 SQL 中足够常见的功能。
  • 当我使用 pgAdmin 运行相同的查询时它给了我一个错误 - 它可能是 postgresql 特定的东西吗? - 好像没有创建别名
  • 然后向我们显示错误。
  • 这个错误会是一个秘密吗?

标签: java sql spring hibernate jpa


【解决方案1】:

来自选择查询末尾的test0_,其中显示:from tests test0_。它或多或少也给你的表一个别名。恕我直言,这看起来不错。

【讨论】:

  • 当我使用 pgAdmin 运行相同的查询时,它给了我一个错误 - 它可能是 postgresql 特定的东西吗? - 好像没有创建别名
【解决方案2】:

实际上,我自己想通了 - 很抱歉浪费了时间。显然,postgre 中列的命名约定是使用snake_case,而我使用的是camelCase。这似乎也是 JPA 中的默认命名约定(我通过在 application.properties 文件中设置不同的命名策略来抑制它)。

查询的问题不在于 test0_ 引用,正如其他答案所指出的那样正确,而是选择了数据库中的 camelCase 列。将列重命名为使用 snake_case 后,问题就解决了。

【讨论】:

  • FWIW 认为您的意思是小写。 PostgreSQL 不会在单词之间插入“_”。您定义表/列名称,它只尊重大写、小写或混合大小写(在 PostgreSQL 中引用时为大写和混合)
猜你喜欢
  • 2014-12-20
  • 2020-09-15
  • 2018-04-30
  • 1970-01-01
  • 1970-01-01
  • 2016-01-14
  • 1970-01-01
  • 1970-01-01
  • 2012-11-10
相关资源
最近更新 更多