gpt4 book ai didi

java - 使用 h2 进行 Spring Junit 测试 - 未找到表

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:21:15 26 4
gpt4 key购买 nike

我正在尝试测试我的一项服务,但它突然失败并出现以下异常。

我想弄清楚是什么导致抛出这个异常:

Caused by: org.h2.jdbc.JdbcSQLException: Table "XYZ" not found; SQL statement:
insert into xyz (id, xx_id, yy_id, order, path, place_id, primary) values (null, ?, ?, ?, ?, ?, ?) [42102-183]

连接:

 Creating new JDBC Driver Connection to [jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false]

用于测试的 PersistenceContext:

@Configuration
public class PersistenceContext {

@Bean
public EmbeddedDatabase dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:sql/db-schema.sql")
.build();
}

}

数据库模式.sql

CREATE TABLE xyz(
id int(11) NOT NULL,
xx_id int(11) NULL,
yy_id int(11) NULL,
path varchar(200) NOT NULL,
date_time_added datetime NOT NULL,
"order" int(11) DEFAULT NULL,
"primary" bit(1) DEFAULT NULL,
PRIMARY KEY (id),
CONSTRAINT fk_xx FOREIGN KEY (xx_id) REFERENCES xx (id) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_yy FOREIGN KEY (yy_id) REFERENCES yy (id) ON DELETE NO ACTION ON UPDATE NO ACTION
);

抛出错误的类

private Image addXyzForXX(MultipartFile file, Xx xx) throws ... {
String destDir = resourceService.getPlacesUploadDir();
Xyz xyz = new Xyz();

xyz.setXx(xx);

String filePath = imageUploadService.upload(file, destDir);

java.util.Date dt = new java.util.Date();

java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String currentTime = sdf.format(dt);

xyz.setPath(filePath);
xyz.setDateTimeAdded(currentTime);

xyz.setOrder(1);
xyz.setPrimary(true);

xyz = xyzRepository.save(xyz);
return xyz;
}

Xyz 存储库

@Repository
public interface XyzRepository extends PagingAndSortingRepository<Xyz, Long> {

}

@Entity
@Table(name = "xyz")
public class Xyz{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String path;
private String dateTimeAdded;
private Integer order;
private Boolean primary;

@ManyToOne(optional=true)
@JoinColumn(name = "xxId")
private Xx xx;

[getters and setters for each field]
}

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
public class ImageServiceTest {
@Autowired
private XyzService xyzService;
@Autowired
private XxService xxService;
@Test
public void testArgumentsNullity3() throws Exception {
XX xx = new XX("a", "b", "c", "d", "e");
xx= xxService.addXx(xx);
xyzService.addImage(XxService.Scope.XX, xx,new MockMultipartFile("a","a","image/jpeg", new byte[1024]));
}
}

最佳答案

我找到了真正的问题。

我在最初的帖子中显示的异常消息缺少一些重要的东西。在堆栈跟踪中还有其他内容说“错误的 sql 语法”。我专注于“图像”表,因为这是堆栈跟踪中的第一件事。

在检查了所有可能的已知问题后,我尝试重命名实体中的字段,因为我认为 H2 会将它们解释为关键字。

重命名字段后,一切正常。

关于java - 使用 h2 进行 Spring Junit 测试 - 未找到表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28818859/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com