如何在Spring Boot应用程序(Hibernate+JPA)中从Postgresql中提取图像(lob)



我有一个逻辑,它通过java中的byte[]从f端获取图像,压缩它们,然后将它们存储在Postgresqldb中的一个用数据lob定义的列中。

服务:

public CourseDto createNewCourse(CourseDto newCourseDto) throws SQLException {
Courses course = courseRepositoryDao.findByCourseName(newCourseDto.getCourseName());
if (course == null) {
course = new Courses()
.setCourseName(newCourseDto.getCourseName())
.setCourseDescription(newCourseDto.getCourseDescription())
.setCoursePrice(newCourseDto.getCoursePrice())
.setIsCourseFree(newCourseDto.getIsCourseFree())
.setIsCourseActive(newCourseDto.getIsCourseActive())
.setLogo(compressZLib(newCourseDto.getLogo()));
;
return CourseMapper.toUserDtoFreeCourses(courseRepositoryDao.save(course));
}
throw exception(EntityType.NEWCOURSE, ExceptionType.DUPLICATE_ENTITY, newCourseDto.getCourseName());
}
// compress the image bytes before storing it in the database
public static byte[] compressZLib(byte[] data) {
Deflater deflater = new Deflater();
deflater.setInput(data);
deflater.finish();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] buffer = new byte[1024];
while (!deflater.finished()) {
int count = deflater.deflate(buffer);
outputStream.write(buffer, 0, count);
}
try {
outputStream.close();
} catch (IOException e) {
}
System.out.println("Compressed Image Byte Size - " + outputStream.toByteArray().length);
return outputStream.toByteArray();
}

我尝试检索图像:

public List<CourseDto> getCoureses() {
List<Courses> courses = courseRepositoryDao.findAllByIsCourseFreeAndIsCourseActive(true, true);
List<CourseDto> coursesNameDto = courses
.stream()
.peek(i -> i.setLogo(decompressZLib(i.getLogo())))
.map(course -> modelMapper.map(CourseMapper.toUserDtoFreeCourses(course), CourseDto.class)).collect(Collectors.toList());
System.out.println("**************************" + coursesNameDto + "**********************");
return coursesNameDto;
}
// uncompress the image bytes before returning it to the angular application
public static byte[] decompressZLib(byte[] data) {
Inflater inflater = new Inflater();
inflater.setInput(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] buffer = new byte[1024];
try {
while (!inflater.finished()) {
int count = inflater.inflate(buffer);
outputStream.write(buffer, 0, count);
}
outputStream.close();
} catch (IOException ioe) {
} catch (DataFormatException e) {
}
return outputStream.toByteArray();
}

但我有一个错误:;对象不能在自动提交模式下使用";

我的实体类在徽标上有这个字段:

@Column(name = "picByte", length = 4000)
@Lob
private byte[] logo;

我认为这可能是以下内容的重复:大型对象不能用于自动提交模式

看看它是否能解决你的问题。

最新更新