springboot jpa---->總結一下遇到的問題


Native Query throw exception

  • dto code
import lombok.Value;

@Value
public class IdsOnly {

    Integer id;
    String otherId;
}
  • repository
public interface TestTableRepository extends JpaRepository<TestTable, Integer> {

    @Query(value = "select id, otherId from TestTable where CreationDate > ?1", nativeQuery = true)
    public Collection<IdsOnly> findEntriesAfterDate(Date creationDate);
}
  • service
List<IdsOnly> results = ttRepo.findEntriesAfterDate(theDate);  
  • exception
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [com.example.IdsOnly]

解決方法有兩種

  • 使用NativeQuery:將IdsOnly更換成接口,提供屬性的get方法。
public interface IdsOnly {
    Integer getId();
    String getOtherId();
}
  • 不使用NativeQuery
@Query("select new com.example.IdsOnly(t.id, t.otherId) from TestTable t where t.creationDate > ?1")

Jpa中沒有update方法

jpa中只有save方法,如果你傳遞的對象的主鍵在數據庫中存在,那么就是更新操作。否則就是插入操作。

Delete operation

JpaRepository Not supported for DML operations [delete query]
  • Repository: add @Modifying
@Modifying
void deleteByUserIdAndToolId(Integer userId, Integer toolId);
  • Service: add @Transactional
@Transactional
public void doDeleteUserTool(Integer userId, Integer toolId) {
    userToolMapper.deleteByUserIdAndToolId(userId, toolId);
}

To be continue

Industry is the soul of business and the keystone of prosperity.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM