Java 使用带有Spring数据JPA的自定义查询返回自定义对象
我已经研究了这个问题,找不到合适的答案 我试图在SpringREST应用程序中使用SpringDataJPA自定义查询从表中只返回某些列。然而,查询在执行时总是抛出异常 org.springframework.core.convert.ConverterNotFoundException:未找到能够从类型[java.lang.String]转换为类型[org.forum.api.model.Message]的转换器 我知道可以使用String,但为什么即使我已经在springbootmain的子包中为它创建了模型,消息对象也没有正确地序列化为JSON呢 这是我的模型课Java 使用带有Spring数据JPA的自定义查询返回自定义对象,java,spring-boot,spring-data-jpa,Java,Spring Boot,Spring Data Jpa,我已经研究了这个问题,找不到合适的答案 我试图在SpringREST应用程序中使用SpringDataJPA自定义查询从表中只返回某些列。然而,查询在执行时总是抛出异常 org.springframework.core.convert.ConverterNotFoundException:未找到能够从类型[java.lang.String]转换为类型[org.forum.api.model.Message]的转换器 我知道可以使用String,但为什么即使我已经在springbootmain的子
@实体
@表(name=“message”)
公共类消息{
@身份证
@GeneratedValue(策略=GenerationType.IDENTITY)
@列(name=“text\u id”)
私人长id;
@NotNull
私有字符串作者;
@NotNull
私有字符串文本;
@NotNull
私有字符串接收器;
public long getId(){return id;}
public void setId(长id){this.id=id;}
公共字符串getAuthor(){return author;}
public void setAuthor(字符串作者){this.author=author;}
公共字符串getText(){return text;}
public void setText(字符串文本){this.text=text;}
公共字符串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);
}
@存储库
公共接口MessageRepository扩展了JpaRepository{
@查询(“从消息m中选择m.author,m.text,其中m.id=:id”)
消息findMessageTextById(@Param(“id”)Long id);
}
如果只想检索某些列,可以使用简单的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")
如果只想检索某些列,可以使用简单的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的接口,也可以只使用带有两个getter的接口。