如何使spring bean扩展一个通用的抽象类?

时间:2017-08-08 13:27:17

标签: java spring hibernate spring-data-jpa

由于遗留问题和其他原因,我无法使用JPA存储库。所以我正在尝试为项目构建类似的东西。 我有课MyEntityRepo

DATEFROMPARTS ( left(POSTDATE, 4), right(POSTDATE, 2), substring(POSTDATE,6,2))  > dateadd(day,2,cast(getdate() as date));

并且

@Repository
public class MyEntityRepo extends CustomRepository<MyEntity, Integer> {

}

但是当我启动项目时,spring框架无法创建bean,因为它给出了NullPointerException,因为_clazz字段为null。有人可以解释一下如何实现这个目标吗?

2 个答案:

答案 0 :(得分:0)

据我所知,主要问题是获得泛型类。

您不需要存储T _clazz;

尝试使用org.springframework.core.GenericTypeResolver

_clazz = (Class<T>) GenericTypeResolver.resolveTypeArgument(getClass(), CustomRepository.class);

the second answer

获得逻辑

但实际上Spring Data会在接口上创建代理。见the example

答案 1 :(得分:0)

我还有一种Hibernate使用的方式。

Public Sub RecursiveData()
    Dim connectionString As String = "Initial Catalog=DBName;Data Source=ServerName;uid=user;password=mypassword;Connection Timeout=50000"

    Dim cteQuery As String = ";WITH   cte " & vbCrLf &
        " AS(SELECT 1 AS n " & vbCrLf &
        " UNION ALL " & vbCrLf &
        " SELECT n + 1 " & vbCrLf &
        " FROM   cte " & vbCrLf &
        " WHERE  n <50 " & vbCrLf &
        " ) " & vbCrLf &
        " SELECT n " & vbCrLf &
        " FROM cte where n <= 5; "

    Using _con As New SqlConnection(connectionString)
        Using _cmd As New SqlCommand(cteQuery, _con)

            _con.Open()

            Using rdr As SqlDataReader = _cmd.ExecuteReader()
                While rdr.Read()
                    Console.WriteLine(rdr.GetValue(0).ToString())
                End While

                rdr.Close()
            End Using

            _con.Close()
        End Using
    End Using

End Sub

这对我有用:)