我使用spring和thymeleaf绑定集合时遇到问题。每次我发送表单时,我的对象集合都设置为null(User.postions),我的例子如下:
我的控制器:
@RequestMapping(value = urlFragment + "/add", method = RequestMethod.GET)
public String addPosition(Model model) {
HashSet<Position> positions = new HashSet<Position>(positionRepository.findByEnabledTrueOrderByNameAsc());
User employee = new User();
for (Position position : positions) {
employee.addPosition(position);
}
model.addAttribute("employee", employee);
return "crud/employee/add";
}
@RequestMapping(value = urlFragment + "/add", method = RequestMethod.POST)
public String processNewEmployee(Model model, @Valid @ModelAttribute("employee") User employee, BindingResult result) {
String templatePath = "crud/employee/add";
if (!result.hasErrors()) {
userRepository.save(employee);
model.addAttribute("success", true);
}
return templatePath;
}
我的员工表格:
<form action="#" th:action="@{/panel/employee/add}" th:object="${employee}" method="post">
<div class="row">
<div class="col-md-6">
<label th:text="#{first_name}">First name</label>
<input class="form-control" type="text" th:field="*{userProfile.firstName}"/>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label th:text="#{last_name}">Last name</label>
<input class="form-control" type="text" th:field="*{userProfile.lastName}"/>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label th:text="#{email}">Email</label>
<input class="form-control" type="text" th:field="*{email}"/>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label th:text="#{position}">Position</label>
<select th:field="*{positions}" class="form-control">
<option th:each="position : *{positions}"
th:value="${position.id}"
th:text="${position.name}">Wireframe
</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-5">
<div class="checkbox">
<button type="submit" class="btn btn-success" th:text="#{add_employee}">
Add employee
</button>
</div>
</div>
</div>
</form>
用户实体:
@Entity
@Table(name="`user`")
public class User extends BaseModel {
@Column(unique = true, nullable = false, length = 45)
private String email;
@Column(nullable = false, length = 60)
private String password;
@Column
private String name;
@Column
private boolean enabled;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "user_role",
joinColumns = {@JoinColumn(name = "user_id", nullable = false)},
inverseJoinColumns = {@JoinColumn(name = "role_id", nullable = false)}
)
private Collection<Role> roles = new HashSet<Role>();
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "user_position",
joinColumns = {@JoinColumn(name = "user_id", nullable = false)},
inverseJoinColumns = {@JoinColumn(name = "position_id", nullable = false)}
)
private Collection<Position> positions = new HashSet<Position>();
public User() {
}
public User(String email, String password, boolean enabled) {
this.email = email;
this.password = password;
this.enabled = enabled;
}
public User(String email, String password, boolean enabled, Set<Role> roles) {
this.email = email;
this.password = password;
this.enabled = enabled;
this.roles = roles;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Collection<Position> getPositions() {
return positions;
}
private void setPositions(Collection<Position> positions) {
this.positions = positions;
}
public boolean addPosition(Position position) {
return positions.add(position);
}
public boolean removePosition(Position position) {
return positions.remove(position);
}
public Collection<Role> getRoles() {
return roles;
}
private void setRoles(Collection<Role> roles) {
this.roles = roles;
}
public boolean addRole(Role role) {
return roles.add(role);
}
public boolean removeRole(Role role) {
return roles.remove(role);
}
@Override
public String toString() {
return User.class + " - id: " + getId().toString() + ", email: " + getEmail();
}
}
我已经读过某个地方,我必须创建equals()和hashCode(),所以我在我的位置实体中做了。
public boolean equals(Position position) {
return this.getId() == position.getId();
}
public int hashCode(){
return this.getId().hashCode() ;
}
以下是post方法发送的数据:
这是我的结果:
我的春季版:4.1.6.RELEASE thymeleaf-spring4版本:2.1.4.RELEASE thymeleaf-layout-dialect版本:1.2.8
当然,我希望位置是HashCode,其中一个元素的对象位置为id = 2。 你可以帮帮我吗?我做错了什么?
答案 0 :(得分:1)
这是因为您使用${position.id}
作为选项值。这意味着spring无法计算出值中使用的id与实际Position对象之间的关系。只需${position}
尝试您的价值,它应该有效:
<select th:field="*{positions}" class="form-control">
<option th:each="position : *{positions}"
th:value="${position}"
th:text="${position.name}">Wireframe
</option>
</select>
(确保您已经在您的Position类上实现了hashCode和equals)
如果仍然无法正常工作,则可能必须实现位置格式化,以使转换显式化。请参阅此示例thymeleafexamples-selectmultiple。
答案 1 :(得分:1)
我有类似的问题,我通过添加Formatter类并将Formatter添加到MVC的配置来解决:
@Override
protected void addFormatters(FormatterRegistry registry){
registry.addFormatter(new PositionFormater());
...
}
和位置类格式化程序应如下所示:
PositionFormatter:
public class PositionFormatter implements Formatter<Position>{
/** String representing null. */
private static final String NULL_REPRESENTATION = "null";
@Resource
private PositionRepository positionRepository;
public PositionFormatter() {
super();
}
@Override
public String print(Position position, Locale locale) {
if(position.equals(NULL_REPRESENTATION)){
return null;
}
try {
Position newPosition = new Position();
newPosition.setId(position.getId());
return newPosition.getId().toString();
} catch (NumberFormatException e) {
throw new RuntimeException("Failed to convert `" + position + "` to a valid id");
}
}
@Override
public Position parse(String text, Locale locale) throws ParseException {
if (text.equals(NULL_REPRESENTATION)) {
return null;
}
try {
Long id = Long.parseLong(text);
Position position = new Position();
position.setId(id);
return position;
} catch (NumberFormatException e) {
throw new RuntimeException("Failed to convert `" + text + "` to valid Position");
}
}
}
就我而言,这两个问题解决了所有问题。我有几个格式化程序,我只做一个并将其添加到配置文件(在我的情况下是WebMVCConfig)
答案 2 :(得分:0)
感谢各位回答我的问题。你帮我很多不幸的是,我不得不在一件事上与你不同意。你给我看了例子:
newPosition.setId(position.getId());
同样的例子在Andrew github存储库中。我认为使用setId()方法这是不好的做法。所以我将提出我的解决方案,我将等待一些评论,然后才将其标记为答案。
WebMvcConfig类
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.smartintranet")
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@PersistenceContext
private EntityManager entityManager;
// (....rest of the methods.......)
@Override
public void addFormatters(FormatterRegistry formatterRegistry) {
formatterRegistry.addFormatter(new PositionFormatter(entityManager));
}
}
PositionFormatter类
public class PositionFormatter implements Formatter<Position> {
private EntityManager entityManager;
public PositionFormatter(EntityManager entityManager) {
this.entityManager = entityManager;
}
public String print(Position position, Locale locale) {
if(position.getId() == null){
return "";
}
return position.getId().toString();
}
public Position parse(String id, Locale locale) throws ParseException {
return entityManager.getReference(Position.class, Long.parseLong(id));
}
}
<强> employeeForm.html 强>
<div class="col-md-6">
<label th:text="#{position}">Position</label>
<select th:field="*{position}" class="form-control">
<option th:each="position : ${allPositions}"
th:value="${position.id}"
th:text="${position.name}">Wireframe
</option>
</select>
</div>
最后一个,EmployeeController类
@Controller
public class EmployeeController extends AbstractCrudController {
// (...rest of dependency and methods....)
@Transactional
@RequestMapping(value = urlFragment + "/create", method = RequestMethod.GET)
public String createNewEmployee(Model model) {
prepareEmployeeForm(model);
return "crud/employee/create";
}
@Transactional
@RequestMapping(value = urlFragment + "/create", method = RequestMethod.POST)
public String processNewEmployee(Model model, @ModelAttribute("employee") Employee employee, BindingResult result) {
if (!result.hasErrors()) {
// Look here it is important line!
entityManager.merge(employee.getUser());
}
prepareEmployeeForm(model);
return "crud/employee/create";
}
}
这是我的解决方案。这里有什么不好的?我想那句话:
entityManager.merge(employee.getUser());
我无法在这里使用:
userRepository.save(employee.getUser());
因为Position实体已分离,当我使用save方法时,它会在这种情况下运行em.persist()
,因此我手动运行em.merge()
。我知道这段代码并不完美,但我认为这个解决方案比使用setId()更好。我将感谢建设性的批评者。