GET всегда возвращает значение 0 id. Spring Data JPA - PullRequest
0 голосов
/ 27 марта 2020

спасибо за ваш скорый ответ

В настоящее время я вернулся в этот проект, и я не знаю причину, по которой я всегда получаю 0 в GET-запросе. Я прилагаю все доказательства.

Я получаю ноль в значении PK ID. Но это неверно. Когда я делаю запрос в базе данных, я получаю все правильные значения в порядке.

Я выбираю IDENTITY в PK, чтобы получить автоинкрементные ключи, и в то же время соблюдаю порядок в базе данных и не загрязняю ключи. Я уже знаю, что я мог выбрать последовательность, а также сделал последовательность в моей БД.

Пружинный пыльник, данные пружины jpa, postgreSQL

@Getter
@Setter
@ToString
@Entity
@Table(name = "CATALOGS")
public class Catalogs implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) // usar identity para llave autoincr
    @Column(name = "CAT_ID")
    private int id;

    @NotEmpty(message = "CarName must not be empty")
    @Column(name = "CAT_CAR_NAME")
    private String carName;

    @NotEmpty(message = "CarModel must not be empty")
    @Column(name = "CAT_CAR_MODEL")
    private String carModel;

    @NotEmpty(message = "CarYear must not be empty")
    @Column(name = "CAT_CAR_YEAR")
    private int carYear;

    @NotEmpty(message = "CarVersion must not be empty")
    @Column(name = "CAT_CAR_VERSION")
    private String carVersion;

    @NotEmpty(message = "CarPrice must not be empty")
    @Column(name = "CAT_CAR_PRICE")
    private int carPrice;

    @OneToMany(targetEntity = Items.class, mappedBy = "itemId", orphanRemoval = false, fetch = FetchType.LAZY)
    private Set<Items> catItem;

}

@Repository("catalogsRepository")
@Transactional
public interface CatalogsRepository extends CrudRepository<Catalogs, Integer> {

    List<Catalogs> findAll();

    // I can use Repository interface to return Optional
    Optional<Catalogs> findById(Integer id);


}

@Service("serviceCatalogs")
public class ServiceCatalogsImpl implements ServiceCatalogs {

    public static final Logger LOGGER = LoggerFactory.getLogger(ServiceCatalogsImpl.class);

    @Autowired
    @Qualifier("catalogsRepository")
    private CatalogsRepository catsRepo;

    @Override
    public List<CatalogsModel> findAllCatalogs() {
      //CatalogsModel is a BusinessObject to return and avoid to return the DTO directly

        List<Catalogs> catRep = catsRepo.findAll();
        List<CatalogsModel> lsResp = null;

        if (!catRep.isEmpty()) {

            CatalogsModel target = new CatalogsModel();
            lsResp = new ArrayList<>();

            for (Catalogs catSource : catRep) {
                target.setCarModel(catSource.getCarModel());
                target.setCarName(catSource.getCarName());
                target.setCarPrice(catSource.getCarPrice());
                target.setCarVersion(catSource.getCarVersion());
                target.setCarYear(catSource.getCarYear());
                lsResp.add(target);
            }

            lsResp.stream().forEach(System.out::println);

        }
        return lsResp;
    }
APP YML:

server:
    port: 9080

logging:
    level:
        org:
            springframework: ERROR
spring:
    datasource:
        password:***********
        platform: ***********
        url: 'jdbc:postgresql://localhost:5432/***********'
        username: postgres
    jpa:
        hibernate:
            ddl-auto: validate
            naming:
                physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl    
        properties:
            hibernate: {jdbc: {lob: {non_contextual_creation: true}}}

always return zero 0 in id pk

Ответы [ 3 ]

0 голосов
/ 27 марта 2020

В CatalogsModel вы не устанавливаете идентификатор

Добавить target.setIdCatalog(catSource.getid);

for (Catalogs catSource : catRep) {
                target.setCarModel(catSource.getCarModel());
                target.setCarName(catSource.getCarName());
                target.setCarPrice(catSource.getCarPrice());
                target.setCarVersion(catSource.getCarVersion());
                target.setCarYear(catSource.getCarYear());
                target.setIdCatalog(catSource.getid);
                lsResp.add(target);
}
0 голосов
/ 27 марта 2020

Попробуйте это:

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "CAT_ID")
private int id;
0 голосов
/ 27 марта 2020

Попробуйте изменить

private int id;

на

private Integer id;
...