Created
April 12, 2022 21:10
-
-
Save rponte/6630e8dfcd555d6c31a368efe1176b60 to your computer and use it in GitHub Desktop.
JPA and Hibernate: Bean validation error when merging a transient entity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@SpringBootTest | |
public class NewJpaTest { | |
@Autowired | |
private EntityManager manager; | |
@Test | |
@Transactional | |
public void shouldMergeAnAlbumWithItsImages() { | |
Album album = new Album(List.of(new Image())); | |
Album managedAlbum = manager.merge(album); // throws a ConstraintViolationException due to @Size(min=1) violation | |
assertNull(album.getId()); | |
assertNotNull(managedAlbum.getId()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Entity | |
public class Album { | |
@Id | |
@GeneratedValue(strategy = GenerationType.IDENTITY) | |
private Long id; | |
@Size(min = 1) | |
@OneToMany(cascade = { | |
CascadeType.PERSIST, CascadeType.MERGE | |
}) | |
private List<Image> images = new ArrayList<>(); | |
@Deprecated | |
public Album() {} | |
public Album(List<Image> images) { | |
this.images = images; | |
} | |
public void addImage(Image newImage) { | |
this.images.add(newImage); | |
} | |
public List<Image> getImages() { | |
return this.images; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Entity | |
public class Image { | |
@Id | |
@GeneratedValue(strategy = GenerationType.IDENTITY) | |
private Long id; | |
public Long getId() { | |
return this.id; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://github.com/rafaelpontezup/demo-hibernate-merge-and-validation/blob/master/src/test/java/br/com/zup/edu/demomergewithvalidation/albuns/NewAlbumTest.java#L40