- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 jax-rs/jersey Rest 应用程序,它使用 Hibernate 5.2 作为 orm。还有一个 spring 过滤器使用 token 处理身份验证。一切都运行得很好,但有一个小问题。每个 dao 对象都像这样在构造时创建自己的 session 工厂。
public abstract class BaseDAO<T> {
protected SessionFactory sessionFactory = getSessionFactory();
protected final Validator validator = getValidator();
protected SessionFactory getSessionFactory() {
try {
return (SessionFactory) new Configuration().configure().buildSessionFactory();
} catch (Exception e) {
throw new IllegalStateException("Could not locate SessionFactory in JNDI");
}
}
protected Validator getValidator() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
return factory.getValidator();
}
@SuppressWarnings({"hiding", "unchecked"})
public <T> T save(final T o) {
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
T savedObj = (T) session.save(o);
tx.commit();
session.close();
return savedObj;
}
public void delete(final Object object) {
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
session.delete(object);
tx.commit();
session.close();
}
@SuppressWarnings("hiding")
public <T> T get(final Class<T> type, final int id) {
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
T obj = session.get(type, id);
tx.commit();
session.close();
return obj;
}
@SuppressWarnings({"hiding", "unchecked"})
public <T> T merge(final T o) {
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
T obj = (T) session.merge(o);
tx.commit();
session.close();
return obj;
}
@SuppressWarnings("hiding")
public <T> void saveOrUpdate(final T o) {
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
session.saveOrUpdate(o);
tx.commit();
session.close();
}
@SuppressWarnings({ "hiding", "deprecation", "unchecked" })
public <T> List<T> getAll(final Class<T> type) {
final Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
final Criteria crit = session.createCriteria(type);
List<T> results = crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
tx.commit();
session.close();
return results;
}
@SuppressWarnings({ "hiding", "deprecation", "unchecked" })
public <T> List<T> findByExample(final Class<T> type, T instance) {
try {
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
List<T> results = session
.createCriteria(type)
.add(Example.create(instance))
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.list();
tx.commit();
session.close();
return results;
} catch (RuntimeException re) {
//log.error("find by example failed", re);
throw re;
}
}
这是一个问题,因为如果您创建多个 dao 对象,您很快就会耗尽连接,即使我在每次 dao 调用后调用 session.close() 也是如此。对资源进行过多调用后,我的小型数据库实例提示连接过多。我立即想到的是 session 工厂需要由 Jersey 管理。所以我尝试像这样使用工厂绑定(bind)器:
public class HibernateSessionFactory implements Factory<SessionFactory> {
protected SessionFactory sessionFactory;
@Override
public void dispose(SessionFactory arg0) {
sessionFactory.close();
}
@Override
public SessionFactory provide() {
try {
sessionFactory = (SessionFactory) new Configuration().configure().buildSessionFactory();
return sessionFactory;
} catch (Exception e) {
throw new IllegalStateException("Could not locate SessionFactory in JNDI");
}
}
}
在资源配置中:
register(new AbstractBinder() {
@Override
protected void configure() {
bindFactory(HibernateSessionFactory.class).to(SessionFactory.class);
}
});
并将 BaseDAO 更改为此
@Inject
protected SessionFactory sessionFactory
它似乎不起作用 - session 工厂始终为空。另一个问题是 Spring 过滤器不能使用 Jersey 注入(inject)。过滤器的配置如下。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Order(2)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
private final com.renewedvoices.security.UserService userService;
private final TokenAuthenticationService tokenAuthenticationService;
private final SessionFactory sessionFactory;
public SpringSecurityConfig() {
super(true);
this.userService = new UserService();
this.tokenAuthenticationService = new TokenAuthenticationService("tooManySecrets", userService);
this.sessionFactory = createSessionFactory();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// Custom Token based authentication based on the header previously given to the client
http
.addFilterBefore(new StatelessAuthenticationFilter(tokenAuthenticationService),
UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/rest/auth/**").permitAll()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().and()
.anonymous().and()
.servletApi().and()
.headers().cacheControl();
}
private SessionFactory createSessionFactory() {
try {
return (SessionFactory) new org.hibernate.cfg.Configuration().configure().buildSessionFactory();
} catch (Exception e) {
throw new IllegalStateException("Could not locate SessionFactory in JNDI");
}
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
@Override
public UserService userDetailsService() {
return userService;
}
@Bean
public TokenAuthenticationService tokenAuthenticationService() {
return tokenAuthenticationService;
}
@Bean
public SerssionFactory sessionFactory() {
return sessionFactory;
}
}
无论我在BaseDao中使用@Autowired还是@Inject,sessionFactory总是为null。我无法切换到纯粹的 Spring 。有什么方法可以让这个 sessionFactory 工作吗?这是在休息服务中处理 session 工厂的最佳方法还是有更好的方法不对每个请求打开新 session ?我找到的几乎所有答案都是仅限 Spring 的解决方案。任何帮助是极大的赞赏。
最佳答案
继续我上面的评论
You need to make the DAO a Spring bean so that it can be injected into Spring components. Then for Jersey you need to integrate Jersey to use Spring components so you can inject into Jersey. Have a look at this post.
所以您需要做的就是使 DAO 成为 Spring Bean。你可以这样做
@Configuration
public class DataConfiguration {
@Bean
public MyDao myDao() {
return new MyDao();
}
}
然后在您的 AbstractSecurityWebApplicationInitializer
中,您需要添加配置类,并覆盖 contextConfigLocation
属性,以便 Jersey 不会尝试创建 ContextLoaderListener
。这已经由 Spring Security 创建了
@Order(1)
public class DemoSecurityWebApplicationInitializer
extends AbstractSecurityWebApplicationInitializer {
public DemoSecurityWebApplicationInitializer() {
super(DataConfiguration.class, SecurityConfig.class);
}
@Override
public void afterSpringSecurityFilterChain(ServletContext servletContext) {
// Set the Jersey used property to it won't load a ContextLoaderListener
servletContext.setInitParameter("contextConfigLocation", "NOOP");
}
}
您需要做的最后一件事是添加 jersey-spring3
依赖项。这是 Jersey 依赖项,允许它与 Spring 组件集成(仅 Spring 到 Jersey,而不是 Jersey 到 Spring)。
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
<exclusions>
<!-- exclude Spring 3 if you want to use Spring 4 -->
</exclusions>
<dependency>
请参阅 this GitHub project 中的完整示例。
关于java - Jersey + Hibernate 将 SessionFactory 注入(inject) DAO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41215354/
我使用 hibernate 作为持久层来与数据库通信。我使用 maven 插件 hbm2java 来生成 dao、java、*hbm.xml 和 hibernate.cfg.xml。直到那个时候插件工
我想知道上面提到的 hibernates sessionfactory 类的两种方法之间的概念差异,如果可以通过简单的例子。 最佳答案 前者打开一个正常(有状态) session ,而后者(可能不足为
我正在关注 spring doc entry关于在独立应用程序中以编程方式设置我的应用程序上下文。 主要内容: public class Reporter { public static vo
如果我在结束时用 Session.getCurrentTransaction().commit() 关闭 session 或用 session.close() 关闭 session 会发生什么方法?
我正在尝试在我的 Spring 应用程序中使用 Hibernate 进行 Db 访问。但是现在,我收到以下错误: Could not locate SessionFactory in JNDI jav
我在基于 Java 的配置中使用 Hibernate 和 Spring。我的配置文件是这个: @Bean @Autowired public HibernateTransactionManager t
下面的代码不起作用。问题是事务没有在数据库中提交 案例1: @Transactional public void save(Person p) {
我对这两者有点困惑。据我所知,两者都返回 hibernate session ,SessionFactory.getCurrentSession()返回基于属性 的上下文 session 这是在 h
Image 错误: 1) AdminModel.java - 模型类。 2) HibernateUtil.java 促进 Hibernate DB 连接。 3) AdminDAO.java - 你们知
我遇到此错误,我找不到解决方案 我在Grails中使用postgres 这是不断发生的错误 org.springframework.beans.factory.BeanCreationExceptio
我需要 Hibernate 的一个特定功能,即 StatelessSession,为此我需要 Hibernate 的 SessionFactory。问题是我只有entityManagerFactory
我正在开发 jsf 应用程序并使用 hibernate 作为后端。我想创建 session 工厂并在整个应用程序中关闭它一次。我正在使用 util 类创建 session 工厂。 import org
我正在通过读取项目外部的属性文件来创建 session 工厂。我的属性文件如下, hibernate.connection.driver_class=com.mysql.jdbc.Driver hib
我们有一种情况,我们有多个具有相同模式的数据库,但每个数据库中的数据不同。我们正在创建一个 session 工厂来处理这个问题。 问题是我们不知道我们将连接到哪个数据库,直到运行时我们可以提供它。但是
在我的应用程序中,当我需要在这些方法中访问我的数据库时,我一直在我的方法参数中传递我的 SessionFatory。它在我的 Controller 中实例化,使用: @Autowired privat
我对 DataSource 和 SessionFactory 之间的区别感到困惑。 我认为SessionFactory是一个用于检索 session 的管理器(我猜这实际上是与数据库的连接)。 Dat
我正在尝试学习 spring 3 和 DAO 和 BO 类以及如何使用它进行 Autowiring ,我想知道这是连接 sessionFactory 的正确方法,因为我已经读到它更好地使用 publi
我正在将旧应用程序移植到 Hibernate 5,但在登录阶段遇到了问题。这是它的工作原理(我无法更改): 用户最初使用通用登录名/密码(所有用户相同)连接到 oracle DB 然后用户运行“登录”
根据文档,SessionFactory 应该是线程安全的: An ISessionFactory is threadsafe, many threads can access it concurren
如何使用 java 配置创建 SessionFactory? @Bean public SessionFactory sessionFactory(){ AnnotationSessionFa
我是一名优秀的程序员,十分优秀!