Search code examples
hibernatecastingclasscastexception

How to fix java.lang.ClassCastException in Java


I use version 3.x of hibernate and i have an object X that inherits from a parent object Y. and i have another object Z which has a relation with the object X as follows X OneToMany Z. So the object Z will contain the object X.

I read a lot of questions but it does not answer my problem.

In my XHTML i chose the X object in a dropdown and I retrieve its id to load the object and in my bean i retrieve this ID to load the X object the insertion is done by inserting the object X with null value. when I try to display if the object has been recovered by calling my service this error appears

An Error Occurred:

java.lang.ClassCastException: ma.controle.gestion.modele.Parent_$$_javassist_6 cannot be cast to ma.controle.gestion.modele.Activite

Here is The parent object ( Y )

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="TYPE_OBJET")
@DiscriminatorValue("PARENT")
public class Parent implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
private Long idt_parent;
private String nom;
private String description;
// Getters Setters
}

Here is the Object which inherits from Y ( X )

@Entity
@DiscriminatorValue("ACTIVITE")
public class Activite extends Parent implements Serializable {

private static final long serialVersionUID = 1L;

private String code_sa;

// The mapping of the object Z

@OneToMany(mappedBy="activite",cascade=CascadeType.REMOVE,  orphanRemoval = true)
private Collection<Affectation_Activite> affectation_Activites;

// Getters , setters and construct

}

Here is the modele ( Object Z )

@Entity
public class Affectation_Activite implements Serializable{

/**
 * 
 */
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
private Long idt_affectation_activite;
private Date dateDebut;
private Date dateFin;


@ManyToOne
@JoinColumn(name="idt_parent")
private Activite activite;


// Getters, setters and construct 
}

And here is the fucntion save of my bean

public void save(ActionListener e){




    Activite activite=(Activite)parentService.findParentById(idt_parent);


    System.out.println("Activite nom ====> " + activite .getNom() + " et la description" + activite.getDescription() );

    affectationActivite.setActivite(activite);

    affectationActiviteService.addAffectation(affectationActivite);


}

Solution

  • Solution : I think that this is because as you are using the parent service it is returning a new parent without the values of the Active class. You should use Active service instead

    Related to @Ronce96