Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7570449
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T15:25:47+00:00 2026-05-30T15:25:47+00:00

I’m trying to set up a user case, where I have one generic form

  • 0

I’m trying to set up a user case, where I have one generic form that can handle all types of UploadedFile user uploads. So, here is my setup:

@Entity(name="UploadedForm")
@Table(name="uploaded_file")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="type",discriminatorType=DiscriminatorType.STRING)
public class UploadedFile implements Serializable{

    /** 
     * 
     */
    private static final long serialVersionUID = -6810328674369487649L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id")
    protected Long id;

    @Column(name="name")
    protected String name = null;

    @Column(name="bytes",unique=true)
    @Lob
    protected byte[] bytes;

    @Column(name="type",nullable=false, updatable=false, insertable=false)
    protected String type;


    @ManyToOne(fetch=FetchType.LAZY, targetEntity=User.class)
    @JoinColumn(name="user_id")
    protected User user;

    @Column(name="date_submitted")
    @Temporal(TemporalType.DATE)
    protected Date dateSubmitted;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public Date getDateSubmitted() {
        return dateSubmitted;
    }
    public void setDateSubmitted(Date dateSubmitted) {
        this.dateSubmitted = dateSubmitted;
    }

    @PrePersist
    @PreUpdate
    public void populateDateSubmitted(){
        this.dateSubmitted = new java.sql.Date(new java.util.Date().getTime());
    }
    public byte[] getBytes() {
        return bytes;
    }
    public void setBytes(byte[] bytes) {
        this.bytes = bytes;
    }
    public String getType() {
        return type;
    }

}


@Entity(name="Document")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorValue(value="Document")
public class DocumentFile extends UploadedFile {

    public void setDateSubmitted(Date dateSubmitted) {
        this.dateSubmitted = dateSubmitted;
    }

    @PrePersist
    @PreUpdate
    public void populateDateSubmitted(){
        this.dateSubmitted = new java.sql.Date(new java.util.Date().getTime());
    }
    public byte[] getBytes() {
        return bytes;
    }
    public void setBytes(byte[] bytes) {
        this.bytes = bytes;
    }
}


@RequestMapping( value="{type}",method=RequestMethod.GET )
    public String showForm(ModelMap model, @PathVariable("type") String type){
        UploadedFile form = null;
        if((model.get("FORM") == null)){
            if(type.equals("document")){
                form =  new DocumentFile();
            }
            else if( type.equals("image")){
                form =  new ImageFile();
            }
        }else{
            form = (UploadedFile)model.get("FORM");
            if(form.getClass() == DocumentFile.class)
                form = (DocumentFile)form;
            else if(form.getClass() == ImageFile.class)
                form = (ImageFile)form;
        }


        model.addAttribute("message", "Please select your file and hit submit.");

        model.addAttribute("FORM", form);

        model.addAttribute("type", type);

        return "upload_form";
    }
    @RequestMapping( method=RequestMethod.POST )
    public String processForm(Model model, @RequestParam(value="type") String type, @ModelAttribute(value="FORM") UploadedFile form,BindingResult result, Principal principal) throws FileSaveException, Exception{
        if(!result.hasErrors()){

            UploadedFile savedFile = null;

            try {
                // Find the currently logged in user.  There has to be a more eloquent way...
                String username = principal.getName();
                User user = uService.findByName(username);

                // Set the associated user to the UploadedFile
                form.setUser(user);

                if(type.equals("document"))
                    form = (DocumentFile)form;
                else if(type.equals("image"))
                    form = (ImageFile)form;

                // Persist the file
                savedFile = this.saveFile(form);
            } catch (Exception e) {

                FileSaveException fse =  new FileSaveException("Unable to save file: " + e.getMessage());

                fse.setStackTrace(e.getStackTrace());

                throw fse;

            }
            model.addAttribute("message", "SUCCESS!");
            model.addAttribute("FORM", savedFile);
            return "upload_success";

        }else{

            return "upload_form";

        }
    }

<%@ include file="/WEB-INF/views/includes.jsp" %>
<%@ page session="false" %>
<%@ include file="/WEB-INF/views/header.jsp" %>
<head>
<title>upload</title>
</head>
<body>
    <h1>Upload Stuff -</h1>
    ${message}
    <br />
    <br />

    <form:form commandName="FORM" action="/upload"
        enctype="multipart/form-data" method="POST">
        <input type="hidden" name="type" value="${ type }"/>
        <table>
            <tr>
                <td colspan="2" style="color: red;"><form:errors path="*"
                        cssStyle="color : red;" /> ${errors}</td>
            </tr>
            <tr>
                <td>Name :</td>
                <td>
                    <form:input type="text" path="name" />
                </td>
            </tr>
            <tr>
                <td>File:</td>
                <td>
                    <form:input type="file" path="bytes" />
                </td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="Upload File" />
                </td>
            </tr>
        </table>
    </form:form>
    <br />
    <a href="/">Go home</a>
</body>
<%@ include file="/WEB-INF/views/footer.jsp"%>

And the error I’m getting is:

Unable to cast Object UploadedFile to DocumentFile

Any idea why?

UPDATE: I found a workaround by not passing around the UploadedFile, instead passing the Concrete class I actually want to persist. I also had to remove the controller/service/dao methods and create one for each UploadedFile child. Seems like there should be a better way to do this. Please give your suggestions. Thank you in advance! 🙂

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T15:25:48+00:00Added an answer on May 30, 2026 at 3:25 pm

    Your problem looks to be more about Spring than Hibernate. This:

    @ModelAttribute(value="FORM") UploadedFile form
    

    Spring has no way of knowing, when it translates the incoming request, that you want it to create a DocumentFile instaead of an UploadedFile. It may be possible to create your own ConversionService, but it’s probably easier just to have different request-mappings for your different forms. Like

    @RequestMapping(value="/post/uploadedfile", method=RequestMethod.POST )
    public String processUploadedFileForm(Model model, @RequestParam(value="type") String type, @ModelAttribute(value="FORM") UploadedFile form,BindingResult result, Principal principal) throws FileSaveException, Exception{
    ...
    }
    
    @RequestMapping(value="/post/documentfile", method=RequestMethod.POST )
    public String processDocumentFileForm(Model model, @RequestParam(value="type") String type, @ModelAttribute(value="FORM") DocumentFile form,BindingResult result, Principal principal) throws FileSaveException, Exception{
    ...
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a text area in my form which accepts all possible characters from
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to create an if statement in PHP that prevents a single post
I am trying to loop through a bunch of documents I have to put
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.