【问题标题】:Hibernate Dao service instead of repository.JpaRepositoryHibernate Dao 服务而不是 repository.JpaRepository
【发布时间】:2015-12-22 06:39:57
【问题描述】:

我想为我的测试项目使用 dao 和服务层,但由于某种原因,我得到了 java.lang.NullPointerException: null。

这是工作示例:

用户控制器:

public class UserController {

    @Autowired
    private UserRepository repo;

    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public User addUser(@RequestBody User user) {

        return repo.saveAndFlush(user);
    }}

用户存储库:

public interface UserRepository extends JpaRepository<User,String> {

    // Optional<User> findOneByLogin(String login);

}

但我将其替换为:我使用以下教程作为指南 Hibernate JPA DAO Example

用户道

public class UserDao implements UserDaoInterface <User,Integer> {

    private Session currentSession;

    private Transaction currentTransaction;

    public org.hibernate.Session openCurrentSession() {
        currentSession = getSessionFactory().openSession();
        return currentSession;
    }

    public org.hibernate.Session openCurrentSessionwithTransaction() {
        currentSession = getSessionFactory().openSession();
        currentTransaction = currentSession.beginTransaction();
        return currentSession;
    }

    public void closeCurrentSession() {
        currentSession.close();
    }

    public void closeCurrentSessionwithTransaction() {
        currentTransaction.commit();
        currentSession.close();
    }

    private static SessionFactory getSessionFactory() {
        Configuration configuration = new Configuration().configure();
        StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties());
        SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
        return sessionFactory;
    }

    public Session getCurrentSession() {
        return currentSession;
    }

    public void setCurrentSession(Session currentSession) {
        this.currentSession = currentSession;
    }

    public Transaction getCurrentTransaction() {
        return currentTransaction;
    }

    public void setCurrentTransaction(Transaction currentTransaction) {
        this.currentTransaction = currentTransaction;
    }

    public UserDao() {

    }

    @Override
    public void create(User user) {
        getCurrentSession().save(user);
    }

会不会是会话返回 null?为什么以及如何解决这个问题?

用户服务

public class UserService {

    private static UserDao userDao;

    public UserService (){

        userDao = new UserDao();

    }

    public void save (User user){

        userDao.openCurrentSessionwithTransaction();
        userDao.create(user);
        userDao.closeCurrentSessionwithTransaction();


    }

}

最后 用户控制器

公共类用户控制器 {

    private UserService userService;

    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public void addUser(@RequestBody User user) {

        userService.save(user);

    }}

我不知道这是否与此有关,但我也在错误日志中得到了这个

at demo.security.SecurityConfiguration$1.doFilterInternal(SecurityConfiguration.java:119)

公共类 SecurityConfiguration 扩展 WebSecurityConfigurerAdapter {

//For more information check spring documentation
private Filter csrfHeaderFilter() {
    return new OncePerRequestFilter() {
        @Override
        protected void doFilterInternal(HttpServletRequest request,
                                        HttpServletResponse response, FilterChain filterChain)
                throws ServletException, IOException {
            CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
                    .getName());
            if (csrf != null) {
                Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                String token = csrf.getToken();
                if (cookie == null || token != null
                        && !token.equals(cookie.getValue())) {
                    cookie = new Cookie("XSRF-TOKEN", token);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
            filterChain.doFilter(request, response); // this is line 119
        }
    };
}}

application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/login5
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=com.mysql.jdbc.Driver

#Hibernate Configuration:
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.show_sql=true
entitymanager.packages.to.scan=com.spr.model

** 编辑 **

所以我按照 Анатолій Вакалюк 的建议做了 添加了@Repository 和@Service 注解,所以spring 可以管理这个。

但现在我收到以下错误:

org.hibernate.HibernateException: /hibernate.cfg.xml not found

我正在使用 Spring Boot,我需要为此使用 xml 配置吗?

【问题讨论】:

  • 您没有在 UserController 中使用 @Autowired 注释标记 userService 字段?

标签: java spring hibernate spring-boot spring-data


【解决方案1】:

你得到一个 NullPointeException 因为你的 UserDao 不是由 Spring 上下文管理的。你必须用 @Repository 注释你的 DAO,然后你可以像这样在服务中注入/自动装配它:

@Autowire
private UserDao userDao;

您的服务也是如此。您必须使用 @Service 对其进行注释并将其自动装配到您的控制器中。

另外如果你配置了JPA,你需要使用EntityManager而不是Hibernate Session

编辑

如果您想自定义 Spring Data 存储库,您可以使用自定义方法声明自己的接口:

public interface CustomRepository {
  //custom methods here
}

并为其提供实现:

public class CustomRepositoryImpl implements CustomRepository {
    @PersistenceContext
    private EntityManager entityManager;


    //custom methods implementation
}

然后,只需使用自定义界面扩展您的存储库:

public interface SomeRepository extends JpaRepository<Entity, Integer>, CustomRepository {
   //you have both spring data and custom methods here

}

有关详细信息,请参阅本文。 Customize spring data repositories

【讨论】:

  • 所以现在我在用户上使用@Entity,在 UserDao 上使用 Repository,在 UserService 上使用 Service。但是现在我收到以下错误:org.hibernate.HibernateException: /hibernate.cfg.xml not found。我正在使用 spring boot 我需要一个 xml 文件吗?
  • 您需要在配置中添加@EntityScan 注释并指定实体所在的包。docs.spring.io/autorepo/docs/spring-boot/1.2.0.M2/api/org/…
  • 谢谢,你真的帮助我更好地理解了春天。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-22
  • 1970-01-01
  • 1970-01-01
  • 2019-07-31
  • 1970-01-01
  • 2016-06-17
相关资源
最近更新 更多