Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法使用thymeleaf和Spring引导保存实体_Java_Spring_Spring Boot_Thymeleaf - Fatal编程技术网

Java 无法使用thymeleaf和Spring引导保存实体

Java 无法使用thymeleaf和Spring引导保存实体,java,spring,spring-boot,thymeleaf,Java,Spring,Spring Boot,Thymeleaf,我最近开始在JPA和thymeleaf中使用springboot(我主要来自python/flask和node背景),并尝试在我的数据库中创建一个项目。一切都很顺利,我可以添加、删除等等。。项目 我将变量集用户添加到我的项目实体中,如下所示: @Entity @Table(name = "project") public class Project { @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name = "proje

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

我将变量集用户添加到我的项目实体中,如下所示:

@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;
...
}
@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;
} 
@实体
@表(name=“项目”)
公共类项目{
@身份证
@GeneratedValue(策略=GenerationType.AUTO)
@列(name=“project\u id”)
私有int-id;
@列(name=“title”)
@NotEmpty(message=“*请提供标题”)
私有字符串标题;
@列(name=“description”)
私有字符串描述;
@OneToOne(级联=级联类型.ALL)
@JoinTable(name=“project\u lead”,joinColumns=@JoinColumn(name=“project\u id”),inverseJoinColumns=@JoinColumn(name=“user\u id”))
私人用户项目领导;
@多个(级联=级联类型.ALL)
@JoinTable(name=“project\u user”,joinColumns=@JoinColumn(name=“project\u id”),inverseJoinColumns=@JoinColumn(name=“user\u id”))
私人用户;
...
}
用户类如下所示:

@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;
...
}
@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;
} 
@实体
@表(name=“user”)
公共类用户{
@身份证
@GeneratedValue(策略=GenerationType.AUTO)
@列(name=“user\u id”)
私有int-id;
@列(name=“email”)
@电子邮件(message=“*请提供有效电子邮件”)
@NotEmpty(message=“*请提供电子邮件”)
私人字符串电子邮件;
@列(name=“username”)
@NotEmpty(message=“*请提供用户名”)
私有字符串用户名;
@列(name=“password”)
@长度(最小值=5,message=“*您的密码必须至少包含5个字符”)
@NotEmpty(message=“*请提供您的密码”)
@短暂的
私有字符串密码;
@列(name=“enabled”)
启用私有int;
@多个(级联=级联类型.ALL)
@JoinTable(name=“user\u role”,joinColumns=@JoinColumn(name=“user\u id”),inverseJoinColumns=@JoinColumn(name=“role\u id”))
私人设定角色;
...
}
当我没有为项目指定用户时,我可以创建新项目。但是,当我使用多重选择指定用户时,我在创建项目时遇到了问题。在我的表格中,我有:

<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>

对于th:field=“*{users}”的属性“users”,我不断获取“未能将类型为“java.lang.String”的属性值转换为所需类型“java.util.Set”。我不明白为什么th:value=“${user}”被认为是一个字符串,而它应该属于user类。有没有一种方法可以让我简单地获得select的结果,通过它循环并手动将它添加到控制器中到我的对象项目中

我的控制器如下所示:

@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;
...
}
@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;
} 
@RequestMapping(value=“/projects”,method=RequestMethod.GET)
公共模型和视图showProjectForm(){
ModelAndView ModelAndView=新建ModelAndView();
//获取经过身份验证的用户
Authentication auth=SecurityContextHolder.getContext().getAuthentication();
User=userService.findByEmail(auth.getName());
modelAndView.addObject(“用户名”,“欢迎”+user.getUsername()+”(“+user.getEmail()+”));
addObject(“project”,newproject());
modelAndView.addObject(“alluser”,userService.findAll());
setViewName(“项目创建”);
返回模型和视图;
}
@RequestMapping(value=“/projects”,method=RequestMethod.POST)
公共模型和视图processProjectForm(@Valid Project,BindingResult BindingResult){
ModelAndView ModelAndView=新建ModelAndView();
//获取经过身份验证的用户
Authentication auth=SecurityContextHolder.getContext().getAuthentication();
User=userService.findByEmail(auth.getName());
//获取所有项目
列出所有项目=projectService.findAll();
//检查项目是否已经存在
Project projectExist=projectService.findbytle(Project.getTitle());
if(projectExist!=null){
绑定结果
.rejectValue(“标题”、“错误.项目”,
“已存在具有此标题的项目”);
}
//获取所有用户
List alluser=userService.findAll();
if(bindingResult.hasErrors()){
modelAndView.addObject(“用户名”,“欢迎”+user.getUsername()+”(“+user.getEmail()+”));
addObject(“project”,newproject());
modelAndView.addObject(“allUsers”,allUsers);
setViewName(“项目创建”);
}否则{
//创建项目
project.setProjectLead(用户);
projectService.saveProject(project);
modelAndView.addObject(“用户名”,“欢迎”+user.getUsername()+”(“+user.getEmail()+”));
addObject(“成功”,“项目成功创建!”);
addObject(“project”,newproject());
添加对象(“项目”,所有项目);
modelAndView.setViewName(“重定向:/secure/dashboard”);
}
返回模型和视图;
} 

我能够修复属性“用户”的“未能将类型为“java.lang.String”的属性值转换为所需类型“java.util.Set”的问题。我只需要添加一个转换器类,告诉我如何从字符串转换到用户对象

@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);
}
}
@组件
公共类StringToUser实现转换器{
@自动连线
私人用户服务;
@凌驾
公共用户转换(字符串arg0){
整数id=新整数(arg0);
返回userService.findOne(id);
}
}
并将表单中的选项更改为user.id值,而不是user对象。转换器将处理其余部分:

<option th:each="user : ${allUsers}" th:value="${user.getId()}" th:text="${user.getUsername()}"></option>