gpt4 book ai didi

java - Hibernate Dao 服务而不是repository.JpaRepository

转载 作者:行者123 更新时间:2023-12-02 04:21:03 27 4
gpt4 key购买 nike

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

这是工作示例:

用户 Controller :

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

用户Dao

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);
}

session 会不会返回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();


}

}

最后用户 Controller

公共(public)类 UserController {

    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)

公共(public)类 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
}
};
}}

应用程序属性

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 配置吗?

最佳答案

您收到 NullPointeException,因为您的 UserDao 不受 Spring 上下文管理。您必须使用 @Repository 注释您的 DAO,然后您可以在服务中注入(inject)/ Autowiring 它,如下所示:

@Autowire
private UserDao userDao;

您的服务也是如此。您必须使用 @Service 对其进行注释并在 Controller 中 Autowiring 它。

此外,如果您配置了JPA,则需要使用EntityManager而不是 hibernate session

编辑

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

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

关于java - Hibernate Dao 服务而不是repository.JpaRepository,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32765096/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com