简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM