@Repository
public class NationalityDAO {
@Autowired
private SessionFactory sessionFactory;
public List<Nationality> findAll() {
return CastService.castList(Nationality.class,
sessionFactory.getCurrentSession()
.createCriteria(Nationality.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list());
}
}
@Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
@Bean
public PlatformTransactionManager transactionManager(@Qualifier("entityManagerFactory") LocalContainerEntityManagerFactoryBean entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory.getObject());
return transactionManager;
}
=============编辑:
下面是我的新配置:
@Configuration
@ComponentScan(basePackages = "com.my.package")
@EnableTransactionManagement
public class ApplicationConf {
@Bean public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder(12);
}
}
实体:
@Entity
@Table(name = "NATIONALITY")
public class Nationality {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "nationality_id")
private int id;
@Column(name = "name")
private String name;
public int getId() {
return id;
}
public void setId(int nationalityId) {
this.id = nationalityId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Service
@Transactional
public class NationalityService {
@Autowired
private NationalityDAO nationalityDAO;
@Transactional
public List<Nationality> findAll() {
return nationalityDAO.findAll();
}
}
@Repository
public class NationalityDAO {
@PersistenceContext
private EntityManager entityManager;
private SessionFactory sessionFactory;
public NationalityDAO() { }
public NationalityDAO(SessionFactory session) {
sessionFactory = session;
if (!session.getCurrentSession().getTransaction().isActive()) {
session.getCurrentSession().beginTransaction();
}
}
public Session getSession() {
if (sessionFactory != null) {
return this.sessionFactory.getCurrentSession();
} else {
return this.entityManager.unwrap(Session.class);
}
}
public List<Nationality> findAll() {
return CastService.castList(Nationality.class,
this.getSession()
.createCriteria(Nationality.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list());
}
}
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.format_sql=false
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.globally_quoted_identifiers=true
spring.jpa.properties.hibernate.connection.CharSet=utf8
spring.jpa.properties.hibernate.connection.characterEncoding=utf8
spring.jpa.properties.jpa.hibernate.connection.useUnicode=true
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
编辑3:
--已删除(字符限制)--
编辑4:
@Repository
public class NationalityDAO {
private static final Logger logger = Logger.getLogger(CandidateDAO.class);
@Autowired
private SessionFactory sessionFactory;
public NationalityDAO() { }
public NationalityDAO(SessionFactory session) {
sessionFactory = session;
if (!session.getCurrentSession().getTransaction().isActive()) {
session.getCurrentSession().beginTransaction();
}
}
public Nationality getById(Integer id) {
Nationality nationality = null;
try {
nationality = (Nationality) sessionFactory.getCurrentSession().get(Candidate.class, id);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return nationality;
}
}
2021-06-15 10:01:10 ERROR NationalityDAO:154 - No CurrentSessionContext configured!
org.hibernate.HibernateException: No CurrentSessionContext configured!
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:489)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.invokeProxyMethod(AbstractEntityManagerFactoryBean.java:519)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean$ManagedEntityManagerFactoryInvocationHandler.invoke(AbstractEntityManagerFactoryBean.java:734)
at com.sun.proxy.$Proxy120.getCurrentSession(Unknown Source)
at com.my.package.repository.NationalityDAO.getById(NationalityDAO.java:152)
at com.my.package.repository.NationalityDAO$$FastClassBySpringCGLIB$$c45d52df.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:779)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:692)
at com.my.package.repository.NationalityDAO$$EnhancerBySpringCGLIB$$3763e5c5.getById(<generated>)
at com.my.package.service.NationalityService.getById(NationalityService.java:74)
at com.my.package.service.NationalityService$$FastClassBySpringCGLIB$$3b96bdf.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:779)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:692)
at com.my.package.service.NationalityService$$EnhancerBySpringCGLIB$$ee4a52fa.getById(<generated>)
at com.my.package.http.controller.NationalityController.fetchById(NationalityController.java:111)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1063)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:121)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at com.my.package.security.JWTAuthorizationFilter.doFilterInternal(JWTAuthorizationFilter.java:34)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:218)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:91)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:110)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:96)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:832)
我不知道这是否是目前最好的解决方案,但我已经简化了每个DAO的构造函数,以便它们将会话作为参数:
@Repository
public class NationalityDAO {
private Session session;
public NationalityDAO(Session session) {
this.session = session;
}
public List<Nationality> findAll() {
return CastService.castList(Nationality.class,
this.session
.createCriteria(Nationality.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list());
}
}
然后,通过JPA检索当前会话的相应服务中发生了神奇的事情:
@Service
@Transactional
public class NationalityService {
private NationalityDAO nationalityDAO;
@Autowired
public NationalityService(EntityManager entityManager) {
if (entityManager.unwrap(Session.class) == null) {
throw new NullPointerException();
}
this.nationalityDAO = new NationalityDAO(entityManager.unwrap(Session.class));
}
}
现在它起作用了。
有人知道如何获得由Spring Boot创建的Hibernate SessionFactory的句柄吗?
问题内容: 我将SEAM与JPA(实现为Seam托管持久性上下文)一起使用,在后备bean中,我将一组实体(ArrayList)加载到后备bean中。 如果不同的用户修改了另一个会话中的实体之一,而我希望将这些更改传播到会话中的集合中,则我有一种方法并尝试了以下方法… 用以下查询 重新执行查询,这只会返回我已经拥有的相同数据(我假设它正在使用一级缓存而不是访问数据库) 调用,这应该从数据库刷新,但
问题内容: 我是Flask的忠实拥护者 -部分是因为它简单,部分是因为它具有很多扩展。但是,Flask是要在WSGI环境中使用的,并且WSGI不是非阻塞的,因此(我相信)对于某些类型的应用程序,它的伸缩性不如Tornado。 由于每个人都有一个将调用函数的URL调度程序,并且两个都将使用Python文件(在Django中,你不启动python文件,但在flask或Tornado中,你可以这样做)这
问题内容: 考虑以下查询: 此查询返回以下结果(Usnig Northwind数据库): 我想将Pivot与Join结合使用来获得以下结果: 我该怎么做? 谢谢 问题答案:
我们现在知道有两种"FreeMarker Ant tasks": FreemarkerXmlTask:它来自于FreeMarker的发布包, 打包到 freemarker.jar 中。 这是使用FreeMarker模板转换XML文档的轻量级的,易于使用的Ant任务。 它的入口源文件(输入文件)是XML文件,和生成的输出文件对应, 这是通过单独模板实现的。也就是说,对于每个XML文件, 模板会被执行
问题内容: 民间, 之前,我只有一个jar文件,并且设置了清单,以便可以简单地以以下方式运行程序: 现在,我将功能分为两个jar文件-MyCore.jar和MyApp.jar。 以下命令有效: 但是我不能让以下工作 我收到ClassNotFoundException。 我更喜欢使用“ -jar”开关。有办法使它起作用吗? 预先感谢您的帮助。 问候, 彼得 问题答案: 我有一个这样的Manifest
问题内容: 有没有办法同时使用LIKE和IN? 我想实现这样的目标。 所以基本上,我希望能够用一堆不同的字符串来匹配该列。是否有另一种方法可以对一个查询执行此操作,还是我必须遍历要查找的字符串数组? 问题答案: 您可以通过在一个查询中将各个LIKE与OR串在一起来完成此操作: 请注意,像LIKE和per-row函数之类的东西并不总是能够很好地扩展。如果表可能会变大,则 可能 需要考虑向表中添加另一
我正在抓取一个谷歌学者个人资料页面,现在我有来自漂亮的汤库的python代码,它从页面上收集数据: 我还拥有selenium库中的python代码,它可以自动打开配置文件页面,单击“显示更多”按钮: 如何将这两个代码块组合起来,以便单击显示更多按钮,并刮掉整个页面?提前感谢!