问题
The code looks like this:
Sensor Class:
@Entity
@Table(name = "sensor")
public class Sensor {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne
private SensorType sensorType;
@NotEmpty
@Size(min = 3, max = 255)
@Column(name = "name")
private String name;
......
}
SensorType:
@Entity
@Table(name = "sensortype")
public class SensorType {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "type")
private String type;
......
}
I get an error when I try to insert a new Sensor, SensorType is null because I'm only sending the SensorType "id" to SensorController from jsp and the controller is expecting a SensorType object.
SensorController:
@Controller
public class SensorController {
@Autowired
private ISensor sensorService;
@RequestMapping(value = "/sensor/add", method = RequestMethod.POST)
public String add(Sensor sensor, BindingResult result, Model model) {
if (result.hasErrors()) {
return "sensorAdd";
}
sensorService.insert(sensor);
return "redirect:/sensors";
}
}
How can I solve this?
回答1:
A typical way of solving this is to specify a converter, this way:
public class IdToSensorTypeConveter implements Converter<Integer, SensorType>{
...
@Override
public SensorType convert(Integer id) {
return this.sensorTypeDao.findById(id);
}
}
Register this converter with Spring:
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="IdToSensorTypeConveter"/>
</set>
</property>
</bean>
<mvc:annotation-driven conversion-service="conversionService"/>
Now, if your submitted form has a field for sensorType in sensor fields, it will automatically be bound to the sensorType returned by the above converter.
来源:https://stackoverflow.com/questions/12100107/spring-mvc-bind-id-to-an-object-in-a-model