如何使用弹簧数据jpa更新实体
我有一个实体和一个 Junit,我想测试更新方法是否正常工作,但是当我从 CrudRepository 调用 save 方法时,我会在我的表中得到一个新条目,而不是更新的实体。
这是我的实体:
@Entity(name = "PERSON")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "PERSON_ID")
private Integer id;
@Column(name = "FIRST_NAME")
private String firstName;
@Column(name = "LAST_NAME")
private String lastName;
//getters and setters
}
这是我的服务类:
@Service
public class PersonServiceImpl implements PersonService {
@Autowired
private PersonRepository personRepository;
@Override
public Person updatePerson(Person oldPerson) throws Exception {
return personRepository.save(oldPerson);
}
}
这是我的存储库
public interface PersonRepository extends CrudRepository<Person, String> {
}
这是我的测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { JPAConfigurationTest.class })
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
@Transactional
public class UpdatePersonServiceIntegrationTest {
@Autowired
PersonService personService;
@Before
public void setUp() throws Exception {
Person person = new Person(1);
person.setFirstName("Nicolas");
person.setLastName("Spessot");
personService.createPerson(person); //This invokes save
}
@Test
public void updatingPerson() throws Exception{
Person person = new Person(1);
person.setFirstName("Juan");
person.setLastName("Riquelme");
personService.updatePerson(person);
Person retrieved = personService.retrievePerson(1); //This invokes findOne
assertEquals(1, person.getId());
assertEquals("Juan", person.getFirstName());
assertEquals("Riquelme", person.getLastName());
}
}
提前致谢