2017-06-17 50 views
2

我是Spring/Java EE的新手,我正在尝试一些教程。 我有两个实体类,User和UserType。 我想创建并保存一个用户。 UserType是创建表单中的一个下拉列表。 你能告诉我如何在创建用户的时候保存UserType吗?Spring MVC:如何发布相关的实体对象并保存在数据库中?

  1. 我应该将它作为UserType对象传递吗?
  2. 我应该只传递UserType的id(Integer)吗?

(只显示下面的代码作为一个例子,它没有完成) 正如你可以看到下面,用户有一个叫做用户类型

public class User { 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Integer id; 
    private String name; 
    @OneToOne 
    private UserType type;//one to one 
} 
public class UserType { 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Integer id; 
    private String name; 
} 

//HTML code for the UserType dropdown 
<select th:field="*{type}"> 
<option th:each="type : ${types}" th:text="${type.name}" th:value="${type.id}"></option> 
</select> 

//Controller save user code 
user.setType(new UserType(Integer.parseInt(type), "")); 
this.userRepo.save(user); 

财产当我尝试运行此我得到“无法将类型'java.lang.String'的属性值转换为属性'type'错误所需的类型'UserType'。

保存具有上述关系的实体的最佳方式是什么?学习这个的资源 非常感谢!

+0

你应该通过用户类型的'id'然后在'service'或''通过id' controller'找到用户类型,并设置它'用户'。 –

回答

2

你应该通过再USERTYPE的idservicecontroller通过id找到用户类型,并设置它user

UserType userType = userTypeRepo.find(Integer.parseInt(type)); 
//check userType!= null 
user.setType(userType); 
this.userRepo.save(user); 
2

控制器字段类型带有type.id。你应该转换成真正的类型(实体或dto),最佳实践 - 它使用DTO。 你可以通过鬃毛的方式将type.id转换为实型对象。

  1. 简单情况(您使用它一个或两个次):

    //在控制器

    用户类型的用户类型= dao.getByTypeId(TYPEID); //通过id从数据库获取对象。 user.setType(userType);

  2. 更好的方法创建转换器spring Coverter documentation(你可以使用这个转换器不仅一次,它applyed所有控制器。一旦创建转换器,在很多地方applyed)。转换器获取type.id并通过type返回userType.id

    @Component public final class UserTypeConverter implements Converter { private Long userTypeId; private UserTypeDao userTypeDao;

    public LocalDateTimeConverter(Long userTypeId) { 
        this.userTypeId= userTypeId; 
    } 
    
    @Override 
    public UserType convert(Long userTypeId) { 
        if (userTypeId== null) { 
         return null; 
        } 
    
        return userTypeDao.findById(userTypeId); 
    } 
    

    }

  3. 属性编辑spring documentation同样的想法,作为转换器,但使用了一点不同的情况:当你与用户类型作为工作文本字符串。看到

很好的例子Spring From the Trenches: Using Type Converters With Spring MVC

简单的例子 Spring MVC - Binding Java Backing Objects with Custom Converters

相关问题