我想为我的测试项目使用dao和服务层但由于某种原因我得到了java.lang.NullPointerException:null。
这是工作示例:
UserController:
public class UserController {
@Autowired
private UserRepository repo;
@RequestMapping(value = "/register",method = RequestMethod.POST)
public User addUser(@RequestBody User user) {
return repo.saveAndFlush(user);
}}
UserRepository:
public interface UserRepository extends JpaRepository<User,String> {
// Optional<User> findOneByLogin(String login);
}
但我将其替换为:我使用以下教程作为指南Hibernate JPA DAO Example
userDAO的
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?为什么以及如何解决这个问题?
UserService
public class UserService {
private static UserDao userDao;
public UserService (){
userDao = new UserDao();
}
public void save (User user){
userDao.openCurrentSessionwithTransaction();
userDao.create(user);
userDao.closeCurrentSessionwithTransaction();
}
}
最后 UserController的
public class 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)
公共类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配置。
答案 0 :(得分:2)
你得到一个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