更新我的实体时,我的旧实体也会更新

When updaiting my entity, my old enity updates too

我正在 JUnit4 中测试我的存储库。我需要检查我的 update() 方法,但是当我更新从存储库获取的实体时,我分离的旧实体也会更新。

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "classpath:testContext.xml" })
    @Transactional
    @FixMethodOrder(MethodSorters.JVM)
    public class RepositoryTestTemplate extends
            AbstractTransactionalJUnit4SpringContextTests {

    }   

    public class CreditCardRepositoryTest extends RepositoryTestTemplate {

        @Autowired
        CreditCardRepository creditCardRepository;

        @Test
      public void updateTest() {
        CreditCard creditCard = new CreditCard();
        String oldNumber = "123456789123";
        String newNumber = "321123456789";
        creditCard.setCardNumber(oldNumber);
        creditCardRepository.save(creditCard);

        CreditCard creditCardToUpdate = creditCardRepository.find(creditCard.getId());
        creditCardToUpdate.setCardNumber(newNumber);
        creditCardRepository.update(creditCardToUpdate);

        CreditCard updatedCreditCard = creditCardRepository.find(creditCard.getId());

        assertNotNull(updatedCreditCard);
        assertEquals(newNumber, updatedCreditCard.getCardNumber());
        assertEquals(newNumber, creditCard.getCardNumber());//This should not be equals and cause Error, but it doesn't!!!
//It looks like it returns updated value.

     }
    }

这是我的存储库

@Repository
public class JpaCreditCardRepository implements CreditCardRepository {
    @PersistenceContext
    EntityManager em;

    @Override
    @Transactional
    public void save(CreditCard creditCard) {
        em.persist(creditCard);
    }

    @Override
    @Transactional
    public void update(CreditCard creditCard) {
        em.merge(creditCard);
    }
}

实体

@Entity
    public class CreditCard {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        protected Long id;

        public void setId(Long id) {
            this.id = id;
        }

        public Long getId() {
            return id;
        }
}

看起来 Repo 的返回值引用了相同的分离实体。真的吗?这让我很困惑。

您的第一个实体未分离。一旦您保存它,它就会被管理。当您随后获取信用卡时,EntityManager 将 return 相同的对象,因为它是保存信用卡对象的同一个 EntityManager 实例,因此该对象仍然被管理。

尝试使用 evict 然后使用内存中的任何对象进行删除

this.getSession().evict(对象);