0

代码如下所示:

传感器类:

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

传感器类型:

@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 为空,因为我只是从 jsp 向 SensorController 发送 SensorType“id”,而控制器需要一个 SensorType 对象。

传感器控制器:

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

我该如何解决这个问题?

4

1 回答 1

1

解决这个问题的典型方法是指定一个转换器,这样:

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

}

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

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

于 2012-08-23T22:54:02.977 回答