@Transactional是否会影响以下测试结果?

时间:2019-08-28 02:19:55

标签: java spring spring-boot jpa spring-data-jpa

我想在将Enum列表放入Entity并在DB中查询该实体时检查是否有Enum。 .contains()的结果因@Transactional而异。是什么原因?

InstagramTest.java

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { Application.class })
@Transactional
@NoArgsConstructor
@Slf4j
public class InstagramTest {
    @Autowired
    private PhotoRepository photoRepository;

    @Before
    public void setup() {
        photoRepository.save(PhotoEntity.builder().tags(List.of(TagsEnum.SELFIE, TagsEnum.DAILY)).build());
    }

    @Test
    public void containsTest() {
        PhotoEntity photo = photoRepository.findAll().stream().findFirst().get();
        List<TagsEnum> tags = photo.getTags();

        System.out.println((tags.contains(TagsEnum.SELFIE))); // true but wtihout @Transactional-> false
        System.out.println((tags.contains(TagsEnum.DAILY))); // true but wtihout @Transactional-> false

        System.out.println((tags.contains(TagsEnum.SELFIE.toString()))); // false but without @Transactional-> true
        System.out.println((tags.contains(TagsEnum.DAILY.toString()))); // false but wtihout @Transactional-> true
    }
}

PhotoEntity.java

@Data
@Entity
@Builder
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class PhotoEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Type(type = "json")
    @JsonRawValue
    @Column(name = "tags", columnDefinition = "json")
    private List<TagsEnum> tags;
}

PhotoEntity.java

@Repository
public interface PhotoRepository extends JpaRepository<PhotoEntity, Integer> {

}

TagsEnum.java

@Getter
public enum TagsEnum {
    DAILY,
    SELFIE,
    CELEBRITY,
    LOOKBOOK,
    YOLO,
    FOOD,
    PET
}

0 个答案:

没有答案