【发布时间】:2015-11-19 06:22:41
【问题描述】:
我尝试使用 Restful Web 服务更新具有 OneToOne 关系的实体。
我正在使用自定义查询,但它不起作用
@Modifying
@Query("UPDATE Activity a SET a.type = :type WHERE a.id = :uuid")
int setType(@Param("uuid") UUID uuid, @Param("type") long type);
错误:
java.lang.IllegalArgumentException:参数值 [2] 与预期类型不匹配 [com.mezoo.tdc.model.ActivityType (n/a)]
活动豆
@Entity
@Table(name= "Activity")
public class Activity implements Serializable{
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name="uuid", strategy = "uuid2")
@Column(name = "uuid", nullable = false, unique = true, columnDefinition = "BINARY(16)")
private UUID uuid;
@OneToOne(fetch = FetchType.EAGER, cascade={CascadeType.MERGE})
@JoinColumn(name="type", nullable = false)
private ActivityType type;
ActivityType Bean
@Entity
@Table(name= "ActivityType")
public class ActivityType implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(nullable = false, unique = true)
private String code;
@Column(nullable = false)
private String label;
是否可以在没有自定义查询的情况下进行更新? 我想使用如下的 POST 请求:
{"uuid":"9d9fa946-ee6e-408e-9e8a-7a9786a1d362","label":"ACTIVITY", "type":{"id":2}}
更新
活动存储库:
@Transactional
public interface ActivityDao extends CrudRepository<Activity, UUID> {
@Modifying
@Query("UPDATE Activity a SET a.type = :type WHERE a.uuid = :uuid")
int updateType(@Param("uuid") UUID uuid, @Param("type") ActivityType type);
}
活动服务:
@Service
public class ActivityService implements EntityService<Activity,UUID> {
private static final Logger LOGGER = LoggerFactory.getLogger(ActivityService.class);
@Override
public Activity update(Activity activity) {
LOGGER.info("Update ",activity);
Activity updated = activityDao.findOne(activity.getUuid());
if(updated==null) throw new ResourceNotFoundException();
if (activity.getType().getId()!= updated.getType().getId()) {
LOGGER.info("Update ActivityType for Activity "+activity.getUuid(),activity);
activityDao.updateType(updated.getUuid(),activity.getType());
}
updated.setLabel(activity.getLabel());
updated.setDetails(activity.getDetails());
return activityDao.save(updated);
}
谢谢
【问题讨论】:
-
a.type 显然属于 ActivityType 类型,因此您必须传入一个 ActivityType。 SQLNative 查询是解决这个问题的唯一方法,但是你的代码变成了非 OO 的脏黑客。