Home > Mobile >  JPA projection getting results but not matching the columns with the methods in the interface view
JPA projection getting results but not matching the columns with the methods in the interface view

Time:10-19

I am using jpa projection in spring boot project to get some values. I have the following TABLE:

create table `rental_contract`
(
`rental_contract_id` bigint(20) not null,
`object_id`          bigint(20) default null,
`property_id`        bigint(20) default null,
primary key (rental_contract_id),
foreign key (property_id, object_id) references property_object (property_id, object_id)
);

The following entity:

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@NamedEntityGraph(
    name = "RentalContract.WithPropertyObjects",
    attributeNodes = {
            @NamedAttributeNode(value = "propertyObject", subgraph = 
"RentalContract.WithPropertyObjects.Properties")
    },
    subgraphs = {
            @NamedSubgraph(name = "RentalContract.WithPropertyObjects.Properties",
                    attributeNodes = {
                            @NamedAttributeNode(value = "property")
                    })
    }
)
public class RentalContract {

@Id
private Long rentalContractId;


@JoinColumns({
        @JoinColumn(name = "object_id"),
        @JoinColumn(name = "property_id"),
})
@ManyToOne(fetch = FetchType.LAZY)
private PropertyObject propertyObject;
}

The repository:

public interface RentalContractRepository extends JpaRepository<RentalContract, Long> {

Optional<RentalContract> 
findByPropertyObject_ObjectIdAndPropertyObject_Property_PropertyId(Long objectId, Long 
propertyId);

@Override
@EntityGraph(value = "RentalContract.WithPropertyObjects")
List<RentalContract> findAll();

@Query(value = "SELECT * from rental_contract", nativeQuery = true)
List<RentalContractView> getAllWithObjectsAndProperties();
}

And the view is:

public interface RentalContractView {

Long getRentalContractId();

Long getObjectId();

Long getPropertyId();

}

When I am calling the repository method I can see that I am getting the results and the exact number, but when calling the method getRentalContractId() I am getting null even though there should be a value (checked in the database) and the two other fields are not being mapped.

I tried also with creating class and map them but still not working.

CodePudding user response:

You have to provide aliases for the columns to match the names in the interface:

@Query(value = "SELECT "  
               "rental_contract_id as rentalContractId "  
               "object_id          as objectId "  
               "property_id        as propertyId"  
               "from rental_contract", nativeQuery = true)

There is no naming strategy because you are not using entities.

  • Related