Skip to content

Weird Error about Hibernate Proxy Class Cast Exception #3362

@gunb0s

Description

@gunb0s

I found some weird behavior of hibernate proxy, when casting.

when using findById of jpa repository,
some time hibernate proxy returns and sometime real entity returns.

i'm using

hibernate-core:6.4.1.Final
spring-data-jpa:3.2.2

My entity setting is like below

@Entity
@Table(name = "users")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "dtype")
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Getter
public abstract class User {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "user_id")
	private Long id;

	private String name;

	@Column(updatable = false, insertable = false)
	private String dtype;

	public User(String name) {
		this.name = name;
	}
}

@Entity
@Getter
@DiscriminatorValue("S")
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Student extends User {
	@Builder
	public Student(String name) {
		super(name);
	}
}

And i did find query

Post post = postRepository.findPostWithLecture(createCommentDto.getPostId()).orElseThrow();
Lecture lecture = post.getBoard().getLecture();
User user = userRepository.findById(createCommentDto.getUserId()).orElseThrow();

if (user.getDtype().equals("E")) {
	lectureRepository.findByIdAndEducator(lecture.getId(), (Educator) user).orElseThrow();
} else {
	enrollmentRepository.findByStudentAndLecture((Student) user, lecture).orElseThrow();
}

in above case userRepository.findById returns User$HibernateProxy$byHBV0qu
but when useRepository.findById is executed at the beginning of function, it returns just User.

postRepository.findPostWithLecture uses JPQL and i guess this is a root cause of weird return of findById
this function`s implementation is like below

@Query("select p from Post p join fetch p.board where p.id = :postId")
Optional<Post> findPostWithLecture(Long postId);

is this weird return a normal behavior? or bug??

Metadata

Metadata

Labels

for: external-projectFor an external project and not something we can fixstatus: declinedA suggestion or change that we don't feel we should currently apply

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions