【问题标题】:Return custom Object using custom Query with Spring Data JPA使用带有 Spring Data JPA 的自定义查询返回自定义对象
【发布时间】:2018-09-15 20:22:35
【问题描述】:

我研究了问题,但找不到合适的答案。

我试图在我的 Spring Rest 应用程序中使用带有 Spring Data JPA 的自定义查询从表中只返回某些列。但是查询在执行时总是抛出异常。

org.springframework.core.convert.ConverterNotFoundException: 找不到能够从 [java.lang.String] 类型转换为 [org.forum.api.model.Message] 类型的转换器

我知道可以使用 String,但是为什么即使我在 Spring Boot main 的子包中为它创建了模型,Message 对象也没有正确序列化为 JSON?

这是我的模型类。

@Entity
@Table(name="message")
public class Message {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "text_id")
    private long id;

    @NotNull
    private String author;

    @NotNull
    private String text;

    @NotNull
    private String recepient;

    public long getId() {return id;}

    public void setId(long id) {this.id = id;}

    public String getAuthor() {return author;}

    public void setAuthor(String author) {this.author = author;}

    public String getText() {return text;}

    public void setText(String text) {this.text = text;}

    public String getRecepient() {return recepient;}

    public void setRecepient(String recepient) {this.recepient = recepient;}

}

这里是控制器类。

@RestController
@RequestMapping("/api")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @GetMapping("/message/{id}")
    public Message getMessageTextById(@PathVariable(value="id") Long id) {
        return messageService.getMessageTextById(id);       
    }

}

这里是服务类。

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    MessageRepository messageRepo;

    @Override
    public Message getMessageTextById(Long id) {        
        return messageRepo.findMessageTextById(id);     
    }

}

这里是存储库类

@Repository
public interface MessageRepository extends JpaRepository<Message, Long> {


    @Query("SELECT m.author, m.text FROM Message m WHERE m.id = :id")
    Message findMessageTextById(@Param("id") Long id);

}

【问题讨论】:

    标签: java spring-boot spring-data-jpa


    【解决方案1】:

    如果你只想检索某些列,你可以使用一个简单的 bean 类:

    public class CustomMessage{
      private String author;
      private String text;
    
      public CustomMessage(String author, String text) {
        this.author = author;
        this.author = text;
      }
    }
    

    然后从您的存储库中返回一个 bean 实例:

    @Query("SELECT new path_to_class.CustomMessage(m.author, m.text) FROM Message m WHERE m.id = :id")
    

    或检索地图:

     @Query("SELECT new map(m.author as author, m.text as text) FROM Message m WHERE m.id = :id")
    

    【讨论】:

    • 你也可以只使用两个getter的接口。
    猜你喜欢
    • 1970-01-01
    • 2016-07-19
    • 2017-08-11
    • 2015-03-25
    • 2016-04-15
    • 2015-12-07
    • 2017-08-15
    • 2012-09-13
    相关资源
    最近更新 更多