Spring MVC的ID绑定中的对象模型(Spring MVC bind id to an obj

2019-11-01 01:05发布

代码如下所示:

传感器类别:

@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;
    ......
}

我得到一个错误,当我尝试插入一个新的传感器,SensorType为null,因为我只从JSP发送SensorType“ID”到SensorController和控制器期待一个SensorType对象。

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";
  }
}

我该如何解决这个问题?

Answer 1:

解决这个的典型方法是指定一个转换器,这种方式:

public class IdToSensorTypeConveter implements Converter<Integer, SensorType>{
    ...
    @Override
    public SensorType convert(Integer id) {
        return this.sensorTypeDao.findById(id);
    }

}

注册该转换器与弹簧:

<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"/> 

现在,如果你提交的表单在传感器领域的sensorType一个字段,它会自动绑定到上述转换器中返回的sensorType。



文章来源: Spring MVC bind id to an object in a Model