我正在尝试测试我的一个服务,它突然失败并出现以下异常。
我试图找出导致抛出此异常的原因:
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();
}
}
DB-schema.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]));
}
}
答案 0 :(得分:2)
我发现了实际问题。
我在初次发布的帖子中显示的异常消息缺少重要的内容。在堆栈跟踪中还有其他一些东西说“糟糕的SQL语法”。我专注于“图像”表,因为这是堆栈跟踪中的第一件事。
在我检查了所有可能的已知问题后,我尝试重命名我的实体中的字段,因为我认为H2会将它们解释为关键字。
重命名字段后,一切正常。