所以我是使用spring mvc的新手,对于我遵循http://websystique.com/springmvc/spring-mvc-4-and-spring-security-4-integration-example/教程示例的第一个教程。所以我们有一个名为User的数据模型和另一个datamodel userProfile,我们在user和userProfile之间有一个关系,每个用户都有一个或多个userProfile,这里是类
User.java
@Entity
@Table(name="APP_USER")
public class User implements Serializable{
......
@JsonManagedReference
@NotEmpty
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "APP_USER_USER_PROFILE",
joinColumns = { @JoinColumn(name = "USER_ID") },
inverseJoinColumns = { @JoinColumn(name = "USER_PROFILE_ID") })
private Set<UserProfile> userProfiles = new HashSet<UserProfile>();
@JsonBackReference
@OneToMany(mappedBy="user",cascade=CascadeType.ALL,fetch=FetchType.EAGER)
private Set<Car> cars = new HashSet<Car>();
因此,要使用userProfile添加新用户,我们必须为userProfile添加转换器
RoleToUserProfileConverter.java
@Component
public class RoleToUserProfileConverter implements Converter<Object, UserProfile>{
static final Logger logger = LoggerFactory.getLogger(RoleToUserProfileConverter.class);
@Autowired
UserProfileService userProfileService;
/**
* Gets UserProfile by Id
* @see org.springframework.core.convert.converter.Converter#convert(java.lang.Object)
*/
public UserProfile convert(Object element) {
Integer id = Integer.parseInt((String)element);
UserProfile profile= userProfileService.findById(id);
logger.info("Profile : {}",profile);
return profile;
}
}
表单工作正常,我可以添加一个没有任何错误的新用户,之后我创建了另一个关系,我添加了一个与User.java相关的新类Car.java,
Car.java
public class Car implements Serializable {
.........
@JsonManagedReference
@NotNull
@ManyToOne(optional=false)
@JoinColumn(name="user_fk")
private User user;
}
我为用户类添加了一个转换器
StringToUser.java
@Component
public class StringtoUser implements Converter<Object, User>{
@Autowired
UserService userService ;
@Override
public User convert(Object element) {
if (element == null ) {
return null;
}
Integer id = ((User)element).getId();
User user = userService.findById(id);
return user;
}
添加此转换器后,我在用户表单中收到错误,并且Car表单正常工作:
错误:
WARNING: Failed to bind request element: org.springframework.beans.TypeMismatchException: Failed to convert value of type [com.websystique.springmvc.model.User] to required type [com.websystique.springmvc.model.User]; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [com.websystique.springmvc.model.User] to type [@javax.validation.Valid com.websystique.springmvc.model.User] for value 'User [id=null, ssoId=c, password=c, firstName=c, lastName=c, email=c]'; nested exception is java.lang.NullPointerException
当我删除用户转换器时,用户表单工作正常并且在车辆表单中我收到错误:
错误:
org.apache.jasper.JasperException: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'user' available as request attribute
怎么可以做到!!!!!!