简体   繁体   中英

Java spring mvc: IllegalStateException: Cannot convert value of type [java.lang.String] to required type

As the title says i'm having an annoying IllegalStateException in my spring web app. I've been through numerous topics here on SO and other forums, without any luck.

The error occurs when i'm trying to persist a Note (containing a Folder) in my DB.

Here's my controller;

@InitBinder
public void initBinder(WebDataBinder binder){
binder.registerCustomEditor(Folder.class, new FolderEditor());
}

@RequestMapping(value="/notes")
public @ResponseBody List<Note> postNote(@RequestParam("folder") String folderName,                          
@ModelAttribute(value="note")Note note,  BindingResult result){

    folderName = folderName.replaceAll("\\s+","");
    Folder folder = folderService.getFolderByName(folderName);

    noteService.insertNote(note, folder);

    if(result.hasErrors()){
        System.out.println(result.getFieldError());
}

return noteService.getNotes();

}

Here's my NoteServiceImpl;

public String insertNote(Note note, Folder folder) {

    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    tx.begin();

    note.setFolder(folder);
    em.merge(note); //i've used merge *and* persist
            // this is where it goes wrong!

    tx.commit();
    em.close();

    return "Succes!";
}

Here's my Note;

@Entity
@Table(name="note")
public class Note implements Serializable {

@Id @GeneratedValue
private long id;

private String header;
private String text;

@ManyToOne
private Folder folder;

    // + getters and setters
}

Here's my Folder;

@Entity
public class Folder implements Serializable {
@Id @GeneratedValue
private long id;

private String name;

@OneToMany
private List<Note> notes;

@ManyToOne
private User user;

//+ getters and setters

}

Error;

Field error in object 'note' on field 'folder': 
rejected value [ public]; codes [typeMismatch.note.folder,typeMismatch.folder,typeMismatch.com.minimalito.model.Folder,typeMismatch]; 
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: 
codes [note.folder,folder]; arguments []; default message [folder]]; 
default message [Failed to convert property value of type 'java.lang.String' to required type 'com.minimalito.model.Folder' for property 'folder'; 
nested exception is java.lang.IllegalStateException: 
Cannot convert value of type [java.lang.String] to required type [com.minimalito.model.Folder] for property 'folder': no matching editors or conversion strategy found]

Everything was working fine until I tried to persist a Note (with a Folder) in my DB. I am out of options here, does anyone see the problem?

Sorry guys for not including the error, crucial bit of information :-) I've edited my NoteServiceImpl class, now you can see where it goes wrong.

A few possible solutions I have found consist of using a 'converter class', to convert the String to a Folder. So I have tried that, but i'm kinda stuck, I have created a Converter-class like so;

public final class StringToFolder implements Converter<String, Folder> {

@Autowired
FolderServiceImpl folderServiceImpl;

public Folder convert(String source){
    Folder f = folderServiceImpl.getFolderByName(source);

    return f;
}
}

And the config file;

<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <list>
            <bean id="StringToFolderConverter" class="com.minimalito.converter.StringToFolder" />
        </list>
    </property>
</bean>

But I don't really know where exactly I should use this...because as far as I know, I am never passing a String where I should be passing a Folder. I

Remove the code to get the folder object in your controller and pass the folderName String parameter. In your Note Service implementation class use the folderService to do the job.

Use the @Trasactional annotation when you merge your data to the table for managing transaction,

Here's the code

@Transactional
public String insertNote(Note note, String folderName) {
  try{
    EntityManager em = emf.createEntityManager();
    Folder folder = folderService.getFolderByName(folderName);
    note.setFolder(folder);
    em.flush();
    em.merge(note);
  }catch(Exception e){
      e.printStackTrace();
  }
return "Success!";
}

从第一眼看,看来您在数据库表中该属性的类型错误。

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