JPA插入查询 Spring Boot

68bkxrlz  于 2022-12-12  发布在  Spring
关注(0)|答案(1)|浏览(180)

我有一个类City,它是:

@Entity
@Table(name="city",schema="rezervisi")
public class City {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Getter
@Setter
private int id;
@Getter
@Setter
@NotBlank(message = "Name is mandatory")
private String name;
}

现在我想重写发送对象city的保存方法。如果我想发送整个对象而不是单独发送@Params,我该怎么做呢?而且由于ID是生成的,我该如何通过这里的参数处理它呢?
资料档案库类的代码为:

public interface CityRepo extends JpaRepository<City,Integer> {

@Query(value="select id, name from city where id = :id ", nativeQuery = true)
Optional<City> findById(Integer id);

@Query(value="select id, name from city where name = :name ", nativeQuery = true)
City findByName(String name);

@Modifying
@Query(value = "insert into city (id,name) VALUES (:id,:name)", nativeQuery = true)
City save(City city ); // instead City save(@Param("id) int id .... 

void delete(City city);
}
u1ehiz5o

u1ehiz5o1#

1.如果您的服务是CrudRepository,您可以尝试使用repository.save(city)
1.如果出于某种原因,这不是您所需要的,您可以尝试以下方法:

@Modifying
    @Transactional
    @Query(value = "insert into city (id, name) VALUES (?, ?)", nativeQuery = true)
    City save(Long id, String name);
    
    default City save(City city) {
        return save(city.getId(), city.getName());
    }

相关问题