Spring Data JPA自定义native 查询

来源:互联网 发布:餐馆软件 编辑:程序博客网 时间:2024/05/18 14:26

自定义native 查询

主要用到两个注解,@SqlResultSetMapping@NamedNativeQuery,分别表示结果集类型和sql的定义,示例如下

@Entity@SqlResultSetMapping(        name = "TestModel",        classes = {                @ConstructorResult(                        targetClass = TestModel.class,                        columns = {                                @ColumnResult(name = "money", type = BigDecimal.class),                                @ColumnResult(name = "score", type = String.class)                        }                )        })@NamedNativeQuery(        name = "TSchemesEntity.testFind",        query = "select Money money,Score score from T_Schemes, T_SchemesContent where T_Schemes.ID=T_SchemesContent.SchemeID ",        resultSetMapping = "TestModel")@Table(name = "T_Schemes", schema = "dbo", catalog = "db")public class TSchemesEntity {    ...
  • 自定义的数据类要注意类型的定义,如果数据库查询返回BigInteger而字段是Long类型的字段,就会报错Unable to locate appropriate constructor on class
  • 出问题可调试到org.hibernate.loader.custom.ConstructorResultColumnProcessor#resolveConstructor方法,查看返回的实际类型
public interface TSchemesRepository extends JpaRepository<TSchemesEntity, Long> {    @Query(nativeQuery = true)    public List<TestModel> testFind();}
public class TestModel {    private BigDecimal money;    private String score;    public TestModel(BigDecimal money, String score) {        this.money = money;        this.score = score;    }    public BigDecimal getMoney() {        return money;    }    public void setMoney(BigDecimal money) {        this.money = money;    }    public String getScore() {        return score;    }    public void setScore(String score) {        this.score = score;    }}
1 0
原创粉丝点击