Create entities:
@Entity
public class File {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch=FetchType.LAZY)
private Folder folder;
public Long getId() {
return id;
}
public Folder getFolder() {
return folder;
}
public void setFolder(Folder route) {
this.folder = route;
}
}
@Entity
public class Folder {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "folder")
private List<File> folders = new ArrayList<>();
public Long getId() {
return id;
}
public List<File> getATMs() {
return Collections.unmodifiableList(folders);
}
}
@Entity
public class FolderEx extends Folder {
private String description;
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
Then create and persist FolderEx entity and File entity like this:
...
FolderEx folder = new FolderEx();
folder.setDescription("Description");
em.persist(folder);
File file = new File();
file.setFolder(folder);
em.persist(file);
...
After that, if we get File entity by em.find method and get Folder entity by file.getFolder() method, than we can't access to FolderEx.getDescription() method, even with cast:
File file = em.find(File.class, fileId);
Folder folder = file.getFolder();
FolderEx folderEx = (FolderEx) folder;
And, if execute this code, we see, that actual instance of folder is FolderEx:
System.out.println(Hibernate.getClass(folder));
I attach complete test with this situation |