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?
A typical way of solving this is to specify a converter, this way:
Register this converter with Spring:
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.