无法使用Spring Data JPA提取具有配置文件映像字节[]的用户



我有这个AppUser实体:

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class AppUser implements UserDetails {
@Id
@SequenceGenerator(
name = "appUser_sequence",
sequenceName = "appUser_sequence",
allocationSize = 1
)
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "appUser_sequence"
)
private Integer id;
private String firstname;
private String lastname;
private String email;
private String password;
@Lob
private byte[] profileImage;
private Role role;
// rest of the code

当我尝试使用此方法提取AppUserService中的用户时:

@Override
public AppUser loadUserByUsername(String email) throws UsernameNotFoundException {
return repository.searchByEmail(email)
.orElseThrow(()-> new UsernameNotFoundException("Email not found"));
}
我得到这个错误:org.springframework.orm.jpa.JpaSystemException: Unable to extract JDBC value for position 6

错误是指profileImage,它说JPA无法从用户提取字节数组,(用户成功保存在数据库中,我只是无法从我的postgres数据库中提取)

这是一个服务,它接收一个64字串表示图像,并将其编码为字节数组:

public AuthenticationResponse register(RegistrationRequest registerRequest) {
byte[] profileImageBytes = null;
if (registerRequest.getProfileImageData() != null)
profileImageBytes = Base64.getDecoder().decode(registerRequest.getProfileImageData());


AppUser appUserToRegister = AppUser.builder()
.firstname(registerRequest.getFirstname())
.lastname(registerRequest.getLastname())
.email(registerRequest.getEmail())
.password(passwordEncoder.encode(registerRequest.getPassword()))
.profileImage(profileImageBytes)
.role(Role.USER)
.build();
appUserService.saveUser(appUserToRegister);
String token = jwtService.generateToken(appUserToRegister);
return new AuthenticationResponse(token);
}

您正在使用Postgres。在这种情况下,有两个选项可以在数据库中存储字节数组。

一种是OID类型,这是一种复合类型,其中内容存储在单独的表中,原始列只包含指向它的整数id。它最多可以占用4tb的数据(旧版本最多可占用2gb)。

另一个是BYTEA类型,这正是您想要使用的。它最多可以占用1gb的数据,对于一张个人资料照片来说绰绰有余。

你正在使用Hibernate 6。它将实体字段的字节数组类型映射到Postgres数据库的BYTEA类型,没有问题。不要使用@Lob注释,因为它会导致Hibernate使用需要作为流读取的OID类型。

<<p>

解决方案/strong>从实体中删除@Lob注释。

免责声明:该解决方案仅适用于Postgres数据库。其他JDBC驱动程序可以以不同的方式处理它。

最新更新