是否可以從表中選擇一個或多個欄位并將其映射到物體中?
目前正在嘗試
@Repository
public interface RoleRepo extends JpaRepository<Role, Long>{
@Query("SELECT r.roleId, r.name FROM role r")
List<Role> getAllRoleNames();
}
我只想要這 2 個值,其余欄位可以null提高效率。我現在得到的錯誤是
ConversionFailedException: Failed to convert from type [java.lang.Object[]] to type
[@org.springframework.data.jpa.repository.Query demo.model.Role] for value '{1, Java Dev}';
nested exception is org.springframework.core.convert.ConverterNotFoundException:
No converter found capable of converting from type [java.lang.Long] to type
[@org.springframework.data.jpa.repository.Query demo.model.Role]] with root cause
那么,當我不能說object.Id = role.roleId(object.Id就是那樣1)時,我該如何進行轉換。
uj5u.com熱心網友回復:
使用 Spring Data,您可以使用預測來完成此任務。
@Entity
public class ExampleEntity {
@Id
private Long id;
@OneToOne
private Person person;
private String name;
// getters and setters
}
.
public interface ExampleProjection {
String getName(); // This must be exactly the same as your entity
}
現在您可以在存盤庫中使用 ExampleProjection,即使存盤庫參考的是 ExampleEntity 而不是 Projection。
public interface ExampleRepository extends Repository<ExampleEntity, Long> {
List<ExampleProjection> findBy();
}
更多資訊在這里:https ://www.baeldung.com/spring-data-jpa-projections
uj5u.com熱心網友回復:
在 Spring 中,您可以使用如下自定義物體:
新角色.java
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class NewRole implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private Long id;
private String name;
}
RoleRepo.java
@Repository
public interface RoleRepo extends JpaRepository<Role, Long> {
@Query("SELECT new NewRole(r.id, r.name) FROM role r")
List<NewRole> getAllRoleNames();
}
祝你好運 !
uj5u.com熱心網友回復:
我只是更改了查詢,以便通過添加一個新的建構式來填充我需要的欄位,而其他欄位將為空。
@Repository
public interface RoleRepo extends JpaRepository<Role, Long>{
@Query("SELECT new demo.model.Role(r.roleId, r.name) FROM role r")
List<Role> getAllRoleNames();
}
@AllArgsConstructor //all arg constructor
@Data
@Entity(name = "role")
public class Role {
public Role(Long roleId, String name) { //half arg constructor
this.roleId = roleId;
this.name = name;
}
@Id
private Long roleId;
private String name;
// more fields, getters, and setters
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/526366.html
標籤:爪哇春天弹簧靴jpa
上一篇:如何使用Python Selenium在懸停元素中獲取這些標簽
下一篇:一起使用IF陳述句和Now()
