简体   繁体   中英

Could not deserialize exception spring boot data jpa

I am using a postgres database and writing backend code using spring data jpa.

Community table:

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "community_table")
@Entity
public class CommunityTable {
    @Id
    @GeneratedValue
    @Column(name = "community_id")
    private Integer communityId;

    @Column(name = "community_name", unique = true, nullable = false)
    private String communityName;

    @Column(name = "creation_date", nullable = false)
    private Date creationDate;

    @Column(name = "rules", columnDefinition = "text")
    private String[] rules;

    @ManyToOne
    @JoinColumn(name = "creator_id", nullable = false)
    private UserTable creatorId;

    @ManyToOne
    @JoinColumn(name = "current_owner", nullable = false)
    private UserTable currentOwner;
}

User table:

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "user_table")
@Entity
public class UserTable {
    @Id
    @GeneratedValue
    @Column(name = "user_id", nullable = false)
    private Integer userId;

    @Column(name = "email", nullable = false, unique = true)
    private String email;

    @Column(name = "username", nullable = false, unique = true)
    private String username;

    @Column(name = "join_date", nullable = false)
    private Date joinDate;

    @Column(name = "hashed_password", nullable = false)
    private String hashedPassword;

    @Column(name = "password", nullable = false)
    private String password;

    @Column(name = "last_logged_in", nullable = false)
    private Date lastLoggedIn;

    @OneToMany(mappedBy = "creatorId")
    private List<CommunityTable> creatorCommunity;

    @OneToMany(mappedBy = "currentOwner")
    private List<CommunityTable> ownerCommunity;
}

Controller code which is failing:

@GetMapping("/community")
    public ResponseEntity getAllCommunities(){
        try{
            return new ResponseEntity<>(userService.getAllCommunities(), HttpStatus.OK);
        }catch (Exception e){
            log.error(e.toString());
            return new ResponseEntity<String>("Unable to fetch all communities", HttpStatus.CONFLICT);
        }
    }

Service code which is causing failure of above controller method:

public List<CommunityTable> getAllCommunities() throws Exception{
        try{
            return communityTableRepository.findAll();
        }catch (Exception e){
            log.error(e.toString());
            throw new Exception("Unable to fetch community due to: "+e.toString());
        }
    }

Exception:

Hibernate: select communityt0_.community_id as communit1_0_, communityt0_.community_name as communit2_0_, communityt0_.creation_date as creation3_0_, communityt0_.creator_id as creator_5_0_, communityt0_.current_owner as current_6_0_, communityt0_.rules as rules4_0_ from community_table communityt0_
2022-01-05 22:34:14.989 ERROR 20231 --- [nio-8080-exec-1] c.e.redditbackend.service.UserService    : org.springframework.orm.jpa.JpaSystemException: could not deserialize; nested exception is org.hibernate.type.SerializationException: could not deserialize
2022-01-05 22:34:14.990 ERROR 20231 --- [nio-8080-exec-1] c.e.r.controller.UserController          : java.lang.Exception: Unable to fetch community due to: org.springframework.orm.jpa.JpaSystemException: could not deserialize; nested exception is org.hibernate.type.SerializationException: could not deserialize

Don't mind log.error. I have annotated both service and controller class with @Log4j2 so that is not the issue over here. Due to some reason I am unable to fetch the list of community-tables.

Any ideas why the said exception might be comming.

The problem here is caused by:

@Column(name = "rules", columnDefinition = "text")
private String[] rules; // <-- column only holds a single string, not an array!

With this columnDefinition, the DB column does not hold a string array but a single string, so it will only work if defined like this:

@Column(name = "rules", columnDefinition = "text")
private String rules; // <-- no array!

In case you want to have multiple (ordered) strings, you might switch to an @ElementCollection :

@ElementCollection
@OrderColumn
@Column(columnDefinition = "text")
private List<String> strings; // (<-- not an array, but a list)

Or if you do need an array and/or you want to store all values inside the single column without the collection table, you can resort to hibernate-types :

implementation 'com.vladmihalcea:hibernate-types-55:2.14.0'

Entity:

@TypeDef(
    name = "string-array", 
    typeClass = StringArrayType.class
)
class MyEntity { // ...

  @Type( type = "string-array" )
  @Column(columnDefinition = "text[]") // <-- column matches entity attribute type
  private String[] strings;

// ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM