如何保存分离的实体并替换一对多关系的内容?
How to save a detached entity and replace the content of a one to many relationship?
当我在分离的实体上调用 save() 时,我想替换一对多关系的内容,但它只添加新的事件而不删除旧的(我不想加载来自数据库的实体)。
是否有清除没有loading/attach实体的关系的设置?
我正在使用 spring-data-jpa。
这是我的服务:
@Component
@Transactional
public class StuffService {
@Autowired
StuffDao stuffDao;
public void save(StuffDto stuffDto) {
// The converter maps the properties into the entity, id included
Stuff stuff= stuffConverter.dtoToBo(stuffDto);
stuffDao.save(stuff);
}
}
Dtos
public class StuffDto {
private Long id;
@NotNull(message = "products-empty")
@Valid
private List<ProductStuffDto> products;
}
public class ProductStuffDto {
Integer order;
String name;
}
实体
@Entity
public class Stuff {
@Id
@GeneratedValue
private Long id;
@OneToMany(mappedBy = "stuff", cascade = CascadeType.ALL)
private List<ProductStuff> products;
}
@Entity
public class ProductStuff {
@Id
@GeneratedValue
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "stuff_id", nullable = false)
private Stuff stuff;
Integer order;
String name;
}
道
public interface StuffDao extends JpaRepository<Stuff, Long> {}
感谢您的帮助。
我找到了解决办法!
我不得不添加孤儿移除。
@OneToMany(mappedBy = "stuff", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
这很奇怪,因为我一直认为 Cascade.ALL 中包含的 Cascade.REMOVE 具有相同的效果...
无论如何,我现在可以将实体保存为分离状态并替换其关系。
谢谢大家
当我在分离的实体上调用 save() 时,我想替换一对多关系的内容,但它只添加新的事件而不删除旧的(我不想加载来自数据库的实体)。
是否有清除没有loading/attach实体的关系的设置?
我正在使用 spring-data-jpa。
这是我的服务:
@Component
@Transactional
public class StuffService {
@Autowired
StuffDao stuffDao;
public void save(StuffDto stuffDto) {
// The converter maps the properties into the entity, id included
Stuff stuff= stuffConverter.dtoToBo(stuffDto);
stuffDao.save(stuff);
}
}
Dtos
public class StuffDto {
private Long id;
@NotNull(message = "products-empty")
@Valid
private List<ProductStuffDto> products;
}
public class ProductStuffDto {
Integer order;
String name;
}
实体
@Entity
public class Stuff {
@Id
@GeneratedValue
private Long id;
@OneToMany(mappedBy = "stuff", cascade = CascadeType.ALL)
private List<ProductStuff> products;
}
@Entity
public class ProductStuff {
@Id
@GeneratedValue
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "stuff_id", nullable = false)
private Stuff stuff;
Integer order;
String name;
}
道
public interface StuffDao extends JpaRepository<Stuff, Long> {}
感谢您的帮助。
我找到了解决办法! 我不得不添加孤儿移除。
@OneToMany(mappedBy = "stuff", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
这很奇怪,因为我一直认为 Cascade.ALL 中包含的 Cascade.REMOVE 具有相同的效果...
无论如何,我现在可以将实体保存为分离状态并替换其关系。
谢谢大家