使用多对一关联查询导致 SQLException

Omk*_*kar 2 java jpa spring-data-jpa

我正在尝试一个与 Spring Data JPA 多对一关联的简单用例,但它导致了 SQLException。

模型是典型的 Order 和 OrderItem 类。

命令

@Entity
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String name;

public Long getId() {
    return id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}
Run Code Online (Sandbox Code Playgroud)

订单项

@Entity
public class OrderItem {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String name;

@ManyToOne
@JoinColumn(name = "fk_order")
private Order order;

public Long getId() {
    return id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Order getOrder() {
    return order;
}

public void setOrder(Order order) {
    this.order = order;
}
}
Run Code Online (Sandbox Code Playgroud)

单元测试

@SpringBootTest
public class MappingTests {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private OrderItemRepository orderItemRepository;

    @Test
    @Transactional
    @Disabled
    public void testManyToOneUnidirectional() {
        Order order = new Order();
        order.setName("order-01");
        orderRepository.save(order);

        OrderItem orderItem = new OrderItem();
        orderItem.setName("item-01");
        orderItem.setOrder(order);
        orderItemRepository.save(orderItem);

//        List<OrderItem> all = orderItemRepository.findAll();
    }
Run Code Online (Sandbox Code Playgroud)

单元测试通过。但是,如果我取消注释该行以从中查找所有项目OrderItemRepository失败,但有以下异常:

2020-11-17 11:37:07.671  WARN 35823 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 42001, SQLState: 42001
2020-11-17 11:37:07.671 ERROR 35823 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : Syntax error in SQL statement "INSERT INTO ORDER[*] (NAME, ID) VALUES (?, ?)"; expected "identifier"; SQL statement:
insert into order (name, id) values (?, ?) [42001-200]
2020-11-17 11:37:07.685  INFO 35823 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test: [DefaultTestContext@6c61a903 testClass = MappingTests, testInstance = com.example.jpademo.MappingTests@5408d4b3, testMethod = testManyToOneUnidirectional@MappingTests, testException = org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [insert into order (name, id) values (?, ?)]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement, mergedContextConfiguration = [WebMergedContextConfiguration@658c5a19 testClass = MappingTests, locations = '{}', classes = '{class com.example.jpademo.JpaDemoApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@66d18979, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@17f7cd29, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@7ee8290b, org.springframework.boot.test.web.reactive.server.WebTestClientContextCustomizer@2e377400, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@e4487af, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@683dbc2c, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@233c0b17], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true]]


org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [insert into order (name, id) values (?, ?)]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement

    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:259)
Run Code Online (Sandbox Code Playgroud)

这里可能缺少什么?谢谢。

Omk*_*kar 5

虽然架构是由休眠创建的,但如果遇到名为“order”的表,它似乎会失败并出现以下错误。我将表重命名为其他名称,它按预期工作。我认为 hibernate 标识order为关键字而不是实体名称。

2020-11-17 16:14:51.097  WARN 126490 --- [         task-1] o.h.t.s.i.ExceptionHandlerLoggedImpl     : GenerationTarget encountered exception accepting command : Error executing DDL "drop table if exists order CASCADE " via JDBC Statement

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "drop table if exists order CASCADE " via JDBC Statement
Run Code Online (Sandbox Code Playgroud)