我正在尝试在SpringBoot中创建一个本机查询返回到DTO。
但是,我的SessionFactory正在返回null
。
我在这里已经阅读了很多问题,但似乎没有人帮忙。
我在这里做错了什么?
application.properties
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
SessionFactoryConfig.class
import org.hibernate.SessionFactory;
import org.hibernate.jpa.HibernateEntityManagerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SessionFactoryConfig {
@Bean
public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) {
return hemf.getSessionFactory();
}
}
ReportAverageCost.class
import lombok.*;
import org.hibernate.SQLQuery;
import org.hibernate.SessionFactory;
import org.hibernate.transform.ResultTransformer;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Date;
import java.util.List;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class ReportAverageCost {
@Autowired
private SessionFactory sessionFactory;
public Date date;
public List getReportAverageCost() throws Exception {
String q = "SELECT (...)";
SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(q);
query.addScalar("date");
ResultTransformer aliasToBean = Transformers.aliasToBean(ReportAverageCost.class);
List result = query.setResultTransformer(aliasToBean).list();
return result;
}
}
答案 0 :(得分:1)
在@Component
课程中定义注释ReportAverageCost
。
答案 1 :(得分:0)
这个网站帮助了我:https://blog.pranavek.com/using-hibernate-sessionfactory-in-spring-boot-app/
所以我的代码是这样的:
<强> application.properties 强>
spring.jpa.properties.hibernate.current_session_context_class=thread
<强> ReportAverageCostRepository.class 强>
@Repository
public class ReportAverageCostRepository {
@Autowired
private SessionFactory sessionFactory;
public List getReportAverageCost() throws Exception {
String q = "SELECT (...)";
Session session = this.sessionFactory.getCurrentSession();
session.beginTransaction();
SQLQuery query = session.createSQLQuery(q);
query.addScalar("date");
query.addScalar("transactionIdentifier");
query.addScalar("amount");
query.addScalar("cost");
query.addScalar("price");
ResultTransformer aliasToBean = Transformers.aliasToBean(ReportAverageCost.class);
List result = query.setResultTransformer(aliasToBean).list();
session.getTransaction().commit();
return result;
}
}
<强> ReportAverageCostController.class 强>
@RestController
@RequestMapping(value = "/api/v1/reports/averageCost")
public class ReportAverageCostController {
@Autowired
ReportAverageCostRepository reportAverageCostRepository;
@RequestMapping(value = "/{pair}", method = RequestMethod.GET)
public List<ReportAverageCost> reportAverageCost() throws Exception {
return reportAverageCostRepository.getReportAverageCost();
}
}