当前位置: 首页 > 知识库问答 >
问题:

无法使用thymeleaf和Spring Boot保存实体

刘阳荣
2023-03-14

我最近开始使用Spring Boot(我主要来自Python/flask和node背景)和JPA和thymeleaf,并且我正在尝试在我的数据库中创建一个项目。一切都很顺利,我可以添加,删除等。项目。

@Entity
@Table(name = "project")
public class Project {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "project_id")
private int id;

@Column(name = "title")
@NotEmpty(message = "*Please provide a title")
private String title;

@Column(name = "description")
private String description;

@OneToOne(cascade = CascadeType.ALL)
@JoinTable(name = "project_lead", joinColumns = @JoinColumn(name = "project_id"), inverseJoinColumns = @JoinColumn(name = "user_id"))
private User projectLead;

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "project_user", joinColumns = @JoinColumn(name = "project_id"), inverseJoinColumns = @JoinColumn(name = "user_id"))
private Set<User> users;
...
}
@Entity
@Table(name = "user")
public class User {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "user_id")
private int id;

@Column(name = "email")
@Email(message = "*Please provide a valid Email")
@NotEmpty(message = "*Please provide an email")
private String email;

@Column(name = "username")
@NotEmpty(message = "*Please provide a username")
private String username;

@Column(name = "password")
@Length(min = 5, message = "*Your password must have at least 5 characters")
@NotEmpty(message = "*Please provide your password")
@Transient
private String password;

@Column(name = "enabled")
private int enabled;

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;
...
}
<form th:action="@{/secure/projects}" th:object="${project}" method="POST">
        <div class="form-group">
            <label th:if="${#fields.hasErrors('title')}" th:errors="*{title}" class="validation-message"></label>
            <input type="text" class="form-control" th:field="*{title}" id="title" th:placeholder="Title" /> 
        </div>

        <div class="form-group">
            <input type="text" class="form-control" th:field="*{description}" id="description" th:placeholder="Description" /> 
        </div>

        <div class="form-group">
            <select th:field="*{users}" class="users-select form-control" multiple="multiple">
              <option th:each="user : ${allUsers}" th:value="${user}" th:text="${user.username}"></option>
            </select>
        </div>


        <button name="Submit" value="Submit" type="Submit" th:text="Create"></button>
   </form>

我的控制器看起来是这样的:

@RequestMapping(value = "/projects", method=RequestMethod.GET)
public ModelAndView showProjectForm() {
    ModelAndView modelAndView = new ModelAndView();
    // Get authenticated user
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    User user = userService.findByEmail(auth.getName());

    modelAndView.addObject("userName", "Welcome " + user.getUsername() + " (" + user.getEmail() + ")");
    modelAndView.addObject("project", new Project());
    modelAndView.addObject("allUsers", userService.findAll());
    modelAndView.setViewName("project_creation");
    return modelAndView;
}

@RequestMapping(value = "/projects", method=RequestMethod.POST)
public ModelAndView processProjectForm(@Valid Project project, BindingResult bindingResult) {
    ModelAndView modelAndView = new ModelAndView();
    // Get authenticated user
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    User user = userService.findByEmail(auth.getName());

    // Get all projects
    List<Project> allProjects = projectService.findAll();

    // Check if project already exists
    Project projectExist = projectService.findByTitle(project.getTitle());
    if(projectExist != null) {
        bindingResult
        .rejectValue("title", "error.project",
                "There is already a project with this title");
    }


    // Get all users
    List<User> allUsers = userService.findAll();

    if(bindingResult.hasErrors()) {
        modelAndView.addObject("userName", "Welcome " + user.getUsername() + " (" + user.getEmail() + ")");
        modelAndView.addObject("project", new Project());
        modelAndView.addObject("allUsers", allUsers);
        modelAndView.setViewName("project_creation");
    } else {

        // Create project
        project.setProjectLead(user);
        projectService.saveProject(project);
        modelAndView.addObject("userName", "Welcome " + user.getUsername() + " (" + user.getEmail() + ")");
        modelAndView.addObject("success", "Project successfully created!");
        modelAndView.addObject("project", new Project());
        modelAndView.addObject("projects", allProjects);
        modelAndView.setViewName("redirect:/secure/dashboard");
    }
    return modelAndView;
} 

共有1个答案

黎鹤轩
2023-03-14

我能够修复“无法将”java.lang.String“类型的属性值转换为属性”users“所需的类型”java.util.set“。我只需添加一个converter类,告诉如何从string转换为User Object。

@Component
public class StringToUser implements Converter<String, User> {

@Autowired
private UserService userService;

@Override
public User convert(String arg0) {
    Integer id = new Integer(arg0);
    return userService.findOne(id);
}
}

并将my form中的选项更改为user.id值,而不是user对象。转换器将处理其余部分:

<option th:each="user : ${allUsers}" th:value="${user.getId()}" th:text="${user.getUsername()}"></option>
 类似资料:
  • 本文向大家介绍SpringBoot中的Thymeleaf用法,包括了SpringBoot中的Thymeleaf用法的使用技巧和注意事项,需要的朋友参考一下 Thymeleaf Thymeleaf是最近SpringBoot推荐支持的模板框架,官网在thymeleaf.org这里。 我们为什么要用Thymeleaf来作为模板引擎呢?官网给了我们一个非常令人信服的解释: Thymeleaf is a m

  • 本文向大家介绍SpringBoot thymeleaf的使用方法解析,包括了SpringBoot thymeleaf的使用方法解析的使用技巧和注意事项,需要的朋友参考一下 1.pom.xml添加相应依赖 2.application.properties 3.common.xml文件,注意文件路径 4.添加TemplateController.java 5.添加app.java 6.访问路径,完成

  • 我在rest api应用程序中使用Springboot 1.5.7,并使用thymeleaf模板从我的api发送电子邮件。但是当我将spring boot的版本更新到2.0.2时,它抛出了404错误,即“错误解析模板”错误,模板可能不存在,或者任何配置的模板解析程序都无法访问“。 下面是application.yml中的配置 pom.xml中的thymeleaf版本 下面是我正在使用的模板结构,

  • 本文向大家介绍SpringBoot引入Thymeleaf的实现方法,包括了SpringBoot引入Thymeleaf的实现方法的使用技巧和注意事项,需要的朋友参考一下 1.Thymeleaf简介 Thymeleaf是个XML/XHTML/HTML5模板引擎,可以用于Web与非Web应用  Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模,

  • 尝试使用springboot MVC和Thymeleaf访问POST方法中的多个对象。 这是控制器。 下面是这些观点: patient.html 和result.html 和bean类是:PatientDataModel.java 另一个bean: 现在,问题是,我需要这两个bean在GET和POST方法中都可以访问。当我运行代码时,它正在执行,但是bean没有值,所有值都是空的。请建议