我已经基于我的存储库和服务在数据库中保存了一个数据。我想通过仅更改玩家ID来与邮递员保存另一个数据,但它不是创建新的实体数据,而是更新现有的实体数据我的问题是如何在找到现有ID时通过服务更新数据。但是,当找到新ID时,会将新数据保存到databse中。
这是我的仓库:
@Repository
@Transactional
public interface CricketPlayerRepository extends CrudRepository<CricketPlayer,String> {
Optional<CricketPlayer> findCricketPlayerByName(String name);
}
这是我的服务
@Service
public class CricketPlayerService {
private CricketPlayerRepository cricketPlayerRepository;
public CricketPlayerService(CricketPlayerRepository cricketPlayerRepository) {
super();
this.cricketPlayerRepository = cricketPlayerRepository;
}
public CricketPlayerService() {
}
public Optional<CricketPlayer> getPlayerByName(String name){
return cricketPlayerRepository.findCricketPlayerByName(name);
}
public CricketPlayer save(CricketPlayer cricketPlayer){
Optional<CricketPlayer> id = cricketPlayerRepository.findById(cricketPlayer.getPlayerId());
if (id.isPresent()){
//code here
}
// if (entityManager.isNew(cricketPlayer)) {
// em.persist(cricketPlayer);
// return cricketPlayer;
// } else {
// return em.merge(cricketPlayer);
// }
return cricketPlayerRepository.save(cricketPlayer);
}
public Iterable<CricketPlayer> findAllPlayers() {
return cricketPlayerRepository.findAll();
}
public Optional<CricketPlayer> findPlayersById(String id) {
return cricketPlayerRepository.findById(id);
}
}
答案 0 :(得分:1)
保存和更新操作基于id值。如果ID存在,则合并(更新)实体,否则保存新实例。因此,在这种情况下无法做到这一点。
答案 1 :(得分:0)
1)如果PlayerId是主键ID,则您将调用merge(entity)。如果存在PlayerId,它将进行更新,否则它将创建新记录。
2)如果PlayrerId不是主键ID。最佳做法是避免将PlayerId作为主键。
在邮递员中,您应该将数据库表的主键ID与PlayerId一起传递。 然后,您调用merge(entity)。它将负责基于主键的创建或更新 id是否为空。
例如,如果您在请求中传递了主键ID,则如下所示。
Entity e = new Entity();
if (entityFromRequest.getId() != null){ //this is the db id from request
//get the entity from db and then change the state
e = entity from db by using id
}
e.setPlayerId = entityFromRequest.getPlayerId
merge(e); // it will create or update record