I'am using spring and hibernate.
My entity:
package com.igorgorbunov3333.core.entities.domain;
import com.igorgorbunov3333.core.entities.enums.Proceeding;
import javax.persistence.*;
import java.util.Date;
/**
* Created by Игорь on 03.04.2016.
*/
#Entity
#Table(name = "cases")
#NamedQueries({
#NamedQuery(name = "getAllCases", query = "SELECT c FROM Case c JOIN FETCH c.client JOIN FETCH c.firstInstance " +
"JOIN FETCH c.secondInstance JOIN FETCH c.thirdInstance JOIN FETCH c.category")
})
public class Case {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "case_number")
private String caseNumber;
#ManyToOne
#JoinColumn(name = "client_id")
private Client client;
#OneToOne
#JoinColumn(name = "first_instance_id")
private FirstInstance firstInstance;
#OneToOne
#JoinColumn(name = "second_instance_id")
private SecondInstance secondInstance;
#OneToOne
#JoinColumn(name = "third_instance_id")
private ThirdInstance thirdInstance;
#Enumerated(EnumType.ORDINAL)
private Proceeding proceeding;
#Temporal(TemporalType.DATE)
#Column(name = "closing_date")
private Date closingDate;
#ManyToOne
#JoinColumn(name = "category_id")
private Category category;
private float price;
public long getId() {
return id;
}
public String getCaseNumber() {
return caseNumber;
}
public Client getClient() {
return client;
}
public FirstInstance getFirstInstance() {
return firstInstance;
}
public SecondInstance getSecondInstance() {
return secondInstance;
}
public ThirdInstance getThirdInstance() {
return thirdInstance;
}
public Proceeding getProceeding() {
return proceeding;
}
public Date getClosingDate() {
return closingDate;
}
public Category getCategory() {
return category;
}
public float getPrice() {
return price;
}
public void setId(long id) {
this.id = id;
}
public void setCaseNumber(String caseNumber) {
this.caseNumber = caseNumber;
}
public void setClient(Client client) {
this.client = client;
}
public void setFirstInstance(FirstInstance firstInstance) {
this.firstInstance = firstInstance;
}
public void setSecondInstance(SecondInstance secondInstance) {
this.secondInstance = secondInstance;
}
public void setThirdInstance(ThirdInstance thirdInstance) {
this.thirdInstance = thirdInstance;
}
public void setProceeding(Proceeding proceeding) {
this.proceeding = proceeding;
}
public void setClosingDate(Date closingDate) {
this.closingDate = closingDate;
}
public void setCategory(Category category) {
this.category = category;
}
public void setPrice(float price) {
this.price = price;
}
}
spring-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" >
<!--#Transaction annotation support -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--Scanning components in base-package (look for annotations) -->
<context:component-scan base-package="com.igorgorbunov3333"/>
<!--Activates various annotations to be detected in bean classes: Spring's #Required and #Autowired and so on-->
<context:annotation-config/>
<!--Обеспечивает работу с транзакциями в Spring -->
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf"/>
</bean>
<!-- Datasource. Источник данных - база MySQL -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/database" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!-- EntityManagerFactory -->
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--Поставщик данных - hibernate-->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<!--поиск сущностей в этом пакете-->
<property name="packagesToScan"
value="com.igorgorbunov3333"/>
<!--детали конфигурации поставщика постоянства (hibernate) -->
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQL5Dialect
</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
</beans>
Here I'm getting NullPointerException:
public Case findById(long id) {
return entityManager.find(Case.class, id);
}
I sure to you - id is correct, but entity can't be found. But when I'm getting all entities all fine:
public List<Case> findAll() {
Query query = entityManager.createNamedQuery("getAllCases");
return query.getResultList();
}
What is the reason?
Full track of NPE:
09-Oct-2016 12:40:41.650 SEVERE [http-nio-8080-exec-7] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [ShowSingleCase] in context with path [] threw exception
java.lang.NullPointerException
at com.igorgorbunov3333.core.entities.service.impl.CaseServiceImpl.findById(CaseServiceImpl.java:32)
at com.igorgorbunov3333.web.servlet.display.single.ShowSingleCase.doGet(ShowSingleCase.java:29)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.logging.log4j.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:71)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:522)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:1096)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:760)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1480)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
My CaseServiceImpl:
package com.igorgorbunov3333.core.entities.service.impl;
import com.igorgorbunov3333.core.entities.domain.Case;
import com.igorgorbunov3333.core.entities.enums.CaseStatus;
import com.igorgorbunov3333.core.entities.service.api.CaseService;
import com.igorgorbunov3333.core.util.DateUtil;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.*;
/**
* Created by Игорь on 27.07.2016.
*/
#Repository
#Service("CaseService")
public class CaseServiceImpl implements CaseService {
#PersistenceContext
private EntityManager entityManager;
public Case findById(long id) {
return entityManager.find(Case.class, id);
}
}
Servlet:
package com.igorgorbunov3333.web.servlet.display.single;
import com.igorgorbunov3333.core.entities.domain.Case;
import com.igorgorbunov3333.core.entities.service.api.CaseService;
import com.igorgorbunov3333.core.entities.service.impl.CaseServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static com.igorgorbunov3333.web.util.Views.SINGLE_CASE_PAGE;
/**
* Created by Игорь on 09.08.2016.
*/
#WebServlet(name = "ShowSingleCase", urlPatterns = "/showSingleCase")
public class ShowSingleCase extends HttpServlet {
private CaseService caseService = new CaseServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
long id = Long.valueOf(request.getParameter("caseID"));
Case c = caseService.findById(id);
request.setAttribute("case", c);
request.getRequestDispatcher(SINGLE_CASE_PAGE).forward(request, response);
}
}
Your problem is in this line:
private CaseService caseService = new CaseServiceImpl();
That's not how dependency injection works. You're instantiating your CaseService object manually. In this case framework won't inject any dependencies so your private EntityManager entityManager; field will be null. Instead you have to annotate your caseService field with #Autowired annotation. That will tell Spring to inject the bean from context:
#Autowired
private CaseService caseService;
The only thing that can be null (is not primitive) on the line you stated that would cause a problem is entityManager, so you're looking for the underlying reason for this, which I don't see in the code you posted.
As you are creating CaseServiceImpl class object by yourself in your servlet class, entityManager object is not autowire automatically by spring and that is the reason you are getting NullPointerException. either you should autowire service class object into servlet class so that spring will resolve entitymanager dependency by itself and provide you fully configured service object or you should set entity manager object into your service class while creating its object in servlet.
Related
Hi,
I got this error and i can`t figure why? all of the defintions in there place and still i have this error while i trying to insert data to my DB.
the "tx:annotation-driven" is in the appconfig-data.xml
I call the add function from "UserController"
What could be the reason it does not work?
Error log:
יול 08, 2016 1:06:23 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [searcher] in context with path [/Searcher] threw exception [Request processing failed; nested exception is org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread] with root cause
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate5.SpringSessionContext.currentSession(SpringSessionContext.java:133)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:454)
at com.searcher.dao.EcommerceImp.add(EcommerceImp.java:28)
at com.searcher.controller.UserController.registration(UserController.java:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:112)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169)
at
Classes
** UserController.java"
package com.searcher.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.searcher.dao.RoleDAO;
import com.searcher.entity.RoleEntity;
import com.searcher.entity.UserEntity;
import com.searcher.service.SecurityService;
import com.searcher.service.UserService;
import com.searcher.validator.UserValidator;
#Controller
public class UserController {
#Autowired
private UserService userService;
#Autowired
private SecurityService securityService;
#Autowired
private UserValidator userValidator;
#Autowired
RoleDAO roleDAO;
#RequestMapping(value = "/registration", method = RequestMethod.GET)
public String registration(Model model) {
model.addAttribute("userForm", new UserEntity());
try {
// Creatinw Role Entity
RoleEntity roleUser = new RoleEntity();
RoleEntity roleAdmin = new RoleEntity();
roleUser.setName("ROLE_USER");
roleAdmin.setName("ROLE_ADMIN");
roleDAO.add(roleUser);
roleDAO.add(roleAdmin);
} catch (Exception e) {
// TODO Auto-generated catch block
throw e;
}
return "registration";
}
#RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(#ModelAttribute("userForm") UserEntity userForm, BindingResult bindingResult, Model model) {
userValidator.validate(userForm, bindingResult);
if (bindingResult.hasErrors()) {
return "registration";
}
userService.add(userForm);
securityService.autologin(userForm.getName(), userForm.getPasswordConfirm());
return "redirect:/welcome";
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model, String error, String logout) {
if (error != null)
model.addAttribute("error", "Your username and password is invalid.");
if (logout != null)
model.addAttribute("message", "You have been logged out successfully.");
return "login";
}
#RequestMapping(value = {"/", "/welcome"}, method = RequestMethod.GET)
public String welcome(Model model) {
return "welcome";
}
}
UserEntity.java
package com.searcher.entity;
import java.util.List;
import java.util.Set;
import javax.persistence.*;
#Entity
#Table(name="user")
public class UserEntity {
#Id
#Column(name="User_Id")
#GeneratedValue
private long Id;
#Column(name="Name")
private String Name;
#Column(name="Password")
private String Password;
#Column(name="Password_Confirm")
private String passwordConfirm;
#Column(name="Phone")
private String Phone;
#Column(name="Email")
private String Email;
#ElementCollection(targetClass=RoleEntity.class)
private Set<RoleEntity> roles;
#ManyToMany
#JoinTable(name = "user_role", joinColumns = #JoinColumn(name = "user_id"), inverseJoinColumns = #JoinColumn(name = "role_id"))
public Set<RoleEntity> getRoles() {
return roles;
}
public void setRoles(Set<RoleEntity> roles) {
this.roles = roles;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
public long getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
#Override
public String toString(){
return "Id = " + Id + ", Name = " + Name + ", Password = " + Password + ", Phone = " + Phone + ", Email = " + Email;
}
}
RoleEntity
package com.searcher.entity;
import java.util.Set;
import javax.persistence.*;
#Entity
#Table(name = "role")
public class RoleEntity {
#Id
#GeneratedValue
#Column(name="Id")
private Long Id;
#Column(name="Name")
private String Name;
#ElementCollection(targetClass=UserEntity.class)
private Set<UserEntity> users;
public Long getId() {
return Id;
}
public void setId(Long id) {
this.Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
this.Name = name;
}
#ManyToMany(mappedBy = "roles")
public Set<UserEntity> getUsers() {
return users;
}
public void setUsers(Set<UserEntity> users) {
this.users = users;
}
}
DAO
UserDAOImp
package com.searcher.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.searcher.entity.UserEntity;
#Repository
public class UserImp implements UserDAO{
private static final Logger logger = LoggerFactory.getLogger(UserDAO.class);
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
#Override
public void add(UserEntity user) {
this.sessionFactory.getCurrentSession().persist(user);
logger.info("UserEntity saved successfully, UserEntity Details="+user);
}
#Override
public void edit(UserEntity user) {
this.sessionFactory.getCurrentSession().update(user);
logger.info("UserEntity updated successfully, UserEntity Details="+user);
}
#Override
public void deleteById(int id) {
UserEntity userToDelete = getUserById(id);
this.sessionFactory.getCurrentSession().delete(userToDelete);
logger.info("UserEntity deleted successfully, UserEntity Details="+userToDelete);
}
#Override
public UserEntity getUserById(int id) {
UserEntity userReturn = (UserEntity)this.sessionFactory.getCurrentSession().get(UserEntity.class, id);
logger.info("UserEntity founded successfully, UserEntity Details="+userReturn);
return userReturn;
}
#Override
public UserEntity getUserByName(String name) {
try{
UserEntity userReturn =
(UserEntity)this.sessionFactory.getCurrentSession().createQuery("from user where Name ='" + name + "'");
if (userReturn != null){
logger.info("UserEntity founded successfully, UserEntity Details="+userReturn);
}
else{
logger.info("UserEntity Not found with Name= "+userReturn);
}
return userReturn;
}catch (Exception ex){
}
return null;
}
#SuppressWarnings({ "unchecked", "deprecation" })
#Override
public List<UserEntity> getAllUser() {
List<UserEntity> userList = this.sessionFactory.getCurrentSession().createQuery("from user").list();
logger.info("List<UserEntity> upload successfully, List<UserEntity> Details="+userList.toString());
return userList;
}
}
RoleDAOIMP
package com.searcher.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.searcher.entity.RoleEntity;
#Repository
public class RoleImp implements RoleDAO {
private static final Logger logger = LoggerFactory.getLogger(RoleDAO.class);
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
#Override
public void add(RoleEntity role) {
this.sessionFactory.getCurrentSession().persist(role);
logger.info("RoleEntity saved successfully, RoleEntity Details="+role);
}
#Override
public void edit(RoleEntity role) {
this.sessionFactory.getCurrentSession().update(role);
logger.info("RoleEntity updated successfully, RoleEntity Details="+role);
}
#Override
public void deleteById(int id) {
RoleEntity roleToDelete = getRoleById(id);
this.sessionFactory.getCurrentSession().delete(roleToDelete);
logger.info("RoleEntity deleted successfully, RoleEntity Details="+roleToDelete);
}
#Override
public RoleEntity getRoleById(int id) {
RoleEntity roleReturn = (RoleEntity)this.sessionFactory.getCurrentSession().get(RoleEntity.class, id);
logger.info("RoleEntity founded successfully, RoleEntity Details="+roleReturn);
return roleReturn;
}
#Override
public RoleEntity getRoleByName(String name) {
RoleEntity roleReturn =
(RoleEntity)this.sessionFactory.getCurrentSession().createNamedQuery("from role where Name =" + name);
logger.info("RoleEntity founded successfully, RoleEntity Details="+roleReturn);
return roleReturn;
}
#SuppressWarnings({ "unchecked", "deprecation" })
#Override
public List<RoleEntity> getAllRole() {
List<RoleEntity> roleList = this.sessionFactory.getCurrentSession().createQuery("from role").list();
logger.info("List<RoleEntity> upload successfully, List<RoleEntity> Details="+roleList.toString());
return roleList;
}
}
UserServiceImp
package com.searcher.service;
import java.util.HashSet;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.searcher.dao.RoleDAO;
import com.searcher.dao.UserDAO;
import com.searcher.entity.UserEntity;
#Service("userService")
public class UserServiceImp implements UserService{
#Autowired
private UserDAO userDAO;
#Autowired
private RoleDAO roleDAO;
//#Autowired(required=true)
#Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
public RoleDAO getRoleDAO() {
return roleDAO;
}
public void setRoleDAO(RoleDAO roleDAO) {
this.roleDAO = roleDAO;
}
public BCryptPasswordEncoder getbCryptPasswordEncoder() {
return bCryptPasswordEncoder;
}
public void setbCryptPasswordEncoder(BCryptPasswordEncoder bCryptPasswordEncoder) {
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
#Override
#Transactional
public void add(UserEntity user) {
try {
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
user.setRoles(new HashSet<>(roleDAO.getAllRole()));
this.userDAO.add(user);
} catch (Exception e) {
// TODO: handle exception
}
}
#Override
#Transactional
public void edit(UserEntity user) {
this.userDAO.edit(user);
}
#Override
#Transactional
public void deleteById(int id) {
this.userDAO.deleteById(id);
}
#Override
#Transactional
public UserEntity getUserById(int id) {
return this.userDAO.getUserById(id);
}
#Override
#Transactional
public UserEntity getUserByName(String name) {
return this.userDAO.getUserByName(name);
}
#Override
#Transactional
public List<UserEntity> getAllUser() {
return this.userDAO.getAllUser();
}
}
RoleServiceImpl
package com.searcher.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.searcher.dao.RoleDAO;
import com.searcher.entity.RoleEntity;
public class RoleServiceImp implements RoleService {
#Autowired
private RoleDAO roleDAO;
public RoleDAO getRoleDAO() {
return roleDAO;
}
public void setRoleDAO(RoleDAO roleDAO) {
this.roleDAO = roleDAO;
}
#Override
#Transactional
public void add(RoleEntity role) {
this.roleDAO.add(role);
}
#Override
#Transactional
public void edit(RoleEntity role) {
this.roleDAO.edit(role);
}
#Override
#Transactional
public void deleteById(int id) {
this.roleDAO.deleteById(id);
}
#Override
#Transactional
public RoleEntity getRoleById(int id) {
return this.roleDAO.getRoleById(id);
}
#Override
#Transactional
public RoleEntity getRoleByName(String name) {
return this.roleDAO.getRoleByName(name);
}
#Override
#Transactional
public List<RoleEntity> getAllRole() {
return (List<RoleEntity>)this.roleDAO.getAllRole();
}
}
This is the folowing configuration files:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>Searcher</display-name>
<!-- Location of Java #Configuration classes that configure the components that makeup this application -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/appconfig-root.xml</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>searcher</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>searcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
-->
<!--
<servlet-mapping>
<servlet-name>searcher</servlet-name>
<url-pattern>/welcome.jsp</url-pattern>
<url-pattern>/welcome.html</url-pattern>
<url-pattern>*.html</url-pattern>
</servlet-mapping>-->
</web-app>
appconfig-root.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<import resource="appconfig-mvc.xml"/>
<import resource="appconfig-data.xml"/>
<import resource="appconfig-security.xml"/>
<!-- Scans within the base package of the application for #Component classes to configure as beans -->
<context:component-scan base-package="com.searcher.*"/>
<!--<context:property-placeholder location="classpath:application.properties"/>-->
</beans>
appconfig-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.1.xsd">
<http auto-config="true">
<intercept-url pattern="/" access="hasRole('ROLE_USER')"/>
<intercept-url pattern="/welcome" access="hasRole('ROLE_USER')"/>
<form-login login-page="/login" default-target-url="/welcome" authentication-failure-url="/login?error" username-parameter="username" password-parameter="password"/>
<logout logout-success-url="/login?logout" />
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="userDetailsServiceImpl">
<password-encoder ref="encoder"></password-encoder>
</authentication-provider>
</authentication-manager>
<beans:bean id="userDetailsServiceImpl" class="com.searcher.service.UserDetailsServiceImpl"></beans:bean>
<beans:bean id="encoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<beans:constructor-arg name="strength" value="11"/>
</beans:bean>
</beans:beans>
appconfig-data.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Configure the data source bean -->
<!-- DataSource -->
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url"
value="jdbc:mysql://localhost:3306/SearcherDB" />
<beans:property name="username" value="root" />
<beans:property name="password" value="root" />
</beans:bean>
<!-- Hibernate 5 SessionFactory Bean definition -->
<beans:bean id="hibernate5AnnotatedSessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>com.searcher.entity.RoleEntity</beans:value>
<beans:value>com.searcher.entity.UserEntity</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
<beans:prop key="hibernate.format_sql">true</beans:prop>
<!-- <beans:prop key="hibernate.hbm2ddl.auto">create</beans:prop> -->
</beans:props>
</beans:property>
</beans:bean>
<!-- User -->
<beans:bean id="userDAO" class="com.searcher.dao.UserImp">
<beans:property name="sessionFactory" ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="userService" class="com.searcher.service.UserServiceImp">
<beans:property name="userDAO" ref="userDAO"></beans:property>
</beans:bean>
<!-- Role -->
<beans:bean id="roleDAO" class="com.searcher.dao.RoleImp">
<beans:property name="sessionFactory" ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Configure the transaction manager bean -->
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
</beans>
appconfig-mvc.xml
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/"/>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:validation</value>
</list>
</property>
</bean>
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.JstlView</value>
</property>
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
You are using non transactional daos in your UserController.registration method:
roleDAO.add(roleUser);
roleDAO.add(roleAdmin);
Use RoleServiceImpl instead.
I am new to spring. I was trying to integrate spring with hibernate but
I am not able to get my entity class Employee using packagesToScan, before this I tried annnotatedClasses as well that too didn't work, I also tried wildcards (com.sfb.**.*) with packagesToScan but no luck yet. FYI I am using javax.persistence.Entity so not an import issue too. Below are my spring.xml file and other along with stacktrace:
Spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/sonoo"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="AnnotatedSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.sfb.model.*" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="employeeDao" class ="com.sfb.dao.EmployeeDaoImpl">
<property name="sessionFactory" ref="AnnotatedSessionFactory"/>
</bean>
<bean id="dateFormat" class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
</bean>
<bean id="employee" class="com.sfb.model.Employee">
<property name="ename" value="Javed"/>
<property name="dob">
<bean factory-bean="dateFormat" factory-method="parse">
<constructor-arg value="2010-09-30" />
</bean>
</property>
<property name="address" ref="address"/>
</bean>
<bean id="address" class="com.sfb.model.Address">
<property name="streetno" value="23"/>
<property name="city" value="Bhilai"/>
</bean>
</beans>
TestEmp.java:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.sfb.dao.EmployeeDao;
import com.sfb.model.Address;
import com.sfb.model.Employee;
public class TestEmp {
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("spring.xml");
EmployeeDao empDao= (EmployeeDao)context.getBean(EmployeeDao.class);
Employee emp = (Employee)context.getBean(Employee.class);
Address addr = (Address)context.getBean(Address.class);
empDao.save(emp,addr);
}
}
Address.java:
package com.sfb.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Address {
#Id
#GeneratedValue
#Column(name="street_no")
private int streetno;
#Column(name="city")
private String city;
public int getStreetno() {
return streetno;
}
public void setStreetno(int streetno) {
this.streetno = streetno;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Employee.java:
package com.sfb.model;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity()
#Table(name="emp")
public class Employee {
#Column(name="e_name")
private String ename;
#Id
#GeneratedValue
#Column(name="e_id")
private int eid;
#Column(name="dob")
private Date dob;
#OneToOne(fetch = FetchType.LAZY, mappedBy = "address", cascade =
CascadeType.ALL)
private Address address;
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
EmployeeDao.java:
package com.sfb.dao;
import com.sfb.model.Address;
import com.sfb.model.Employee;
public interface EmployeeDao {
public void save(Employee emp , Address addr);
}
EmployeeDaoImpl.java
package com.sfb.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.sfb.dao.EmployeeDao;
import com.sfb.model.Address;
import com.sfb.model.Employee;
public class EmployeeDaoImpl implements EmployeeDao {
private SessionFactory sessionFactory;
#Override
public void save(Employee emp , Address addr) {
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
emp.setAddress(addr);
session.persist(emp);
tx.commit();
session.close();
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
Exception StackTrace:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.sfb.model.Employee
at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:548)
at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:1338)
at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:180)
at org.hibernate.event.def.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:487)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:70)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:38)
at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:618)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:592)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:596)
at com.sfb.dao.EmployeeDaoImpl.save(EmployeeDaoImpl.java:20)
at com.sfb.mainemp.TestEmp.main(TestEmp.java:19)
Please help me thanks in advance
full StackTrace of NullpointerException:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'AnnotatedSessionFactory' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1403)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:545)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.sfb.mainemp.TestEmp.main(TestEmp.java:15)
Caused by: java.lang.NullPointerException
at org.hibernate.cfg.OneToOneSecondPass.doSecondPass(OneToOneSecondPass.java:135)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1127)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:296)
at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1112)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:717)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:188)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1460)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1400)
... 12 more
Here is an error (Employee.java):
#OneToOne(fetch = FetchType.LAZY, mappedBy = "address", cascade =
CascadeType.ALL)
private Address address;
mappedBy attribute should only used for inverse size of association, so it is not applicable here.
I guess you are trying to build simple unidirectional association.
It should look something like:
#OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="ADDRESS_ID") /* this is the name of address id column in 'emp' table*/
private Address address;
Here is almost identical example from book.
I have a problem with Spring and Oracle, I can select objects, but I can't update and insert. (I usually use MySql)
Aplication context:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- enabling annotation driven configuration /-->
<context:annotation-config/>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:jdbc.properties" />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="{jdbc.username}"
p:password="${jdbc.password}" />
<bean class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"
c:dataSource-ref="dataSource" />
<bean id="jdbcTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/>
<tx:annotation-driven transaction-manager="jdbcTransactionManager"/>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource" p:jpaVendorAdapter-ref="jpaAdapter">
<property name="loadTimeWeaver">
<bean
class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
<property name="persistenceUnitName" value="namePU"></property>
</bean>
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="${jpa.database}" p:showSql="${jpa.showSql}" />
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="package.repository" />
<context:component-scan base-package="package.service" />
</beans>
jdbc.properties:
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:#172.172.10.83:1521:orcl
jdbc.username=User
jdbc.password=Password
hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
jpa.database = ORACLE
hibernate.generate_statistics = true
hibernate.show_sql = true
jpa.showSql = true
jpa.generateDdl = true
Usuario class
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "USUARIO")
public class Usuario implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "ID_USUARIO")
private String idUsuario;
#Column(name = "LOGIN")
private String login;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ID_AMBITO")
private Ambito ambito;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ID_ROL")
private Rol rol;
public String getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(String idUsuario) {
this.idUsuario = idUsuario;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public Ambito getAmbito() {
return ambito;
}
public void setAmbito(Ambito ambito) {
this.ambito = ambito;
}
public Rol getRol() {
return rol;
}
public void setRol(Rol rol) {
this.rol = rol;
}
}
JPAUsuarioDao
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository(value = "usuarioDao")
public class JPAUsuarioDao implements UsuarioDao {
private EntityManager em = null;
#PersistenceContext
public void setEntityManager(EntityManager em) {
this.em = em;
}
#Override
#Transactional(readOnly = true)
public List<Usuario> getUsuariosList() {
TypedQuery<Usuario> query = em.createQuery("SELECT u FROM Usuario u",
Usuario.class);
return query.getResultList();
}
#Override
#Transactional(readOnly = true)
public Usuario getUsuario(String login) throws NoResultException {
TypedQuery<Usuario> query = em.createQuery("SELECT u FROM Usuario u WHERE u.login ='" + login + "'",
Usuario.class);
return query.getSingleResult() ;
}
#Override
#Transactional(readOnly = false)
public void addUsuario(Usuario usuario) {
em.merge(usuario);
}
}
This is the exception afer em.merge:
TRACE: org.hibernate.action.internal.UnresolvedEntityInsertActions - No unresolved entity inserts that depended on [[package.domain.Usuario#70675c9a-5eb4-4241-aa83-9cdea9211d18]]
TRACE: org.hibernate.action.internal.UnresolvedEntityInsertActions - No entity insert actions have non-nullable, transient entity dependencies.
Thank you
I built app with Spring+Hibernate+Spring Data JPA+PostgreSQL. I have Person class referenced to Marital class at two different resources.
Person has tx_person table at database pg_land.
Marital has tx_marital table at database pg_master.
I could retrieved each other when no relationships between Person and Marital. Problem occured when I built relationships (#ManyToOne and #OneToMany) between two classes.
Test Class
package id.co.p**g.sandbox;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.data.domain.Page;
import id.co.p**g.land.Person;
import id.co.p**g.service.land.PersonService;
public class PersonTest {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:spring-data-app-context.xml");
ctx.load("classpath:datasource.xml");
ctx.refresh();
PersonService personService = ctx.getBean(
"springJpaPersonService", PersonService.class);
Page<Person> requests = personService.getPerson(1);
listSurveys(requests);
}
private static void listSurveys(Page<Person> requests) {
// TODO Auto-generated method stub
System.out.println("List of person");
for(Person request: requests) {
System.out.println(request);
}
}
}
Error Message
Exception in thread "main" org.springframework.data.mapping.PropertyReferenceException: No property no found for type id.co.palmagroup.land.Person
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:74)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:325)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:305)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:269)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:240)
at org.springframework.data.jpa.repository.query.QueryUtils.toJpaOrder(QueryUtils.java:427)
at org.springframework.data.jpa.repository.query.QueryUtils.toOrders(QueryUtils.java:390)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.getQuery(SimpleJpaRepository.java:457)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.getQuery(SimpleJpaRepository.java:438)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:320)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:290)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:358)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy35.findAll(Unknown Source)
at id.co.palmagroup.service.land.PersonImpl.getPerson(PersonImpl.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy39.getPerson(Unknown Source)
at id.co.palmagroup.sandbox.PersonTest.main(PersonTest.java:20)
Person Class
package id.co.p**g.land;
import id.co.p**g.master.Marital;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
#Table(name = "tx_person")
public class Person {
private UUID id;
private String name;
private Marital marital;
#Id
#GeneratedValue(generator = "system-uuid")
#GenericGenerator(name = "system-uuid", strategy = "uuid2")
#Type(type="pg-uuid")
#Column(name = "id")
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
#NotEmpty(message="{validation.formcode.NotEmpty.message}")
#Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#ManyToOne(targetEntity=Marital.class)
#JoinColumn(name="id_marital")
#Type(type="pg-uuid")
public Marital getMarital() {
return marital;
}
public void setMarital(Marital marital) {
this.marital = marital;
}
public String toString() {
return "Person ID: " + id
+ ". Name: " + name
+ ". Marital: " + marital;
}
}
Marital Class
package id.co.p**g.master;
import id.co.p**g.land.Person;
import java.util.Set;
import java.util.UUID;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
#Entity
#Table(name = "m_marital")
public class Marital implements Serializable {
private UUID id;
private String name;
private String description;
private int no;
private Set<Person> persons;
#Id
#GeneratedValue(generator = "system-uuid")
#GenericGenerator(name = "system-uuid", strategy = "uuid2")
#Type(type="pg-uuid")
#Column(name = "id")
public UUID getId() {
return this.id;
}
public void setId(UUID id) {
this.id = id;
}
#Column(name = "name")
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "description")
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#OneToMany(targetEntity=Person.class, mappedBy="marital")
public Set<Person> getPersons() {
return this.persons;
}
#Column(name="no")
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public void setPersons(Set<Person> persons) {
this.persons = persons;
}
public String toString() {
return + no + ". "
+ "Marital ID: " + id
+ " Name: " + name
+ ". Description: " + description;
}
}
Person Implementation Class
package id.co.p**g.service.land;
import java.util.List;
import java.util.UUID;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.google.common.collect.Lists;
import id.co.p**g.land.Person;
import id.co.p**g.repository.land.PersonRepository;
#Service("springJpaPersonService")
#Repository
#Transactional
public class PersonImpl implements PersonService {
// TODO PAGE_SIZE, rubah menjadi konfigurasi parameter.
private static final int PAGE_SIZE = 10;
#Autowired
private PersonRepository personRepository;
#PersistenceContext(unitName="landPersistence")
private EntityManager em;
#Transactional(readOnly=true)
public List<Person> findAll() {
return Lists.newArrayList(personRepository.findAll());
}
public Person save(Person person) {
return personRepository.save(person);
}
public void delete(Person person) {
personRepository.delete(person);
}
#Transactional(readOnly=true)
public Person findById(UUID id) {
return personRepository.findById(id);
}
#Transactional(readOnly=true)
public Page<Person> findAllByPage(Pageable pageable) {
return personRepository.findAll(pageable);
}
#Override
public Page<Person> getPerson(Integer pagenumber) {
PageRequest pagerequest = new PageRequest(pagenumber - 1, PAGE_SIZE, Sort.Direction.ASC, "no");
return personRepository.findAll(pagerequest);
}
}
Marital Implementation Class
package id.co.p**g.service.master;
import java.util.List;
import java.util.UUID;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.google.common.collect.Lists;
import id.co.p**g.master.Marital;
import id.co.p**g.repository.master.MaritalRepository;
#Service("springJpaMaritalService")
#Repository
#Transactional
public class MaritalImpl implements MaritalService {
// TODO PAGE_SIZE, rubah menjadi konfigurasi parameter.
private static final int PAGE_SIZE = 10;
#Autowired
private MaritalRepository maritalRepository;
#PersistenceContext(unitName="masterPersistence")
private EntityManager em;
#Transactional(readOnly=true)
public List<Marital> findAll() {
return Lists.newArrayList(maritalRepository.findAll());
}
#Transactional(readOnly=true)
public Marital findById(UUID id) {
return maritalRepository.findById(id);
}
#Transactional(readOnly=true)
public Page<Marital> findAllByPage(Pageable pageable) {
return maritalRepository.findAll(pageable);
}
#Override
public Page<Marital> getMarital(Integer pagenumber) {
PageRequest pagerequest = new PageRequest(pagenumber - 1, PAGE_SIZE, Sort.Direction.ASC, "name");
return maritalRepository.findAll(pagerequest);
}
}
Application Context
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<!-- LAND -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="emf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="landPersistence"/>
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="packagesToScan" value="id.co.p**g.*" />
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.PostgreSQLDialect
</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- MASTER -->
<bean id="transactionManagerMaster" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emfMaster" />
</bean>
<tx:annotation-driven transaction-manager="transactionManagerMaster" />
<bean id="emfMaster"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="masterPersistence"/>
<property name="dataSource" ref="dataSourceMaster" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="packagesToScan" value="id.co.p**g.*" />
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.PostgreSQLDialect
</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<context:annotation-config />
<context:component-scan base-package="id.co.p**g.service.*" />
<jpa:repositories base-package="id.co.p**g.repository.land"
entity-manager-factory-ref="emf" transaction-manager-ref="transactionManager" />
<jpa:repositories base-package="id.co.p**g.repository.master"
entity-manager-factory-ref="emfMaster" transaction-manager-ref="transactionManagerMaster" />
</beans>
Data Source Configuration File
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/pg_land" />
<property name="username" value="sysland" />
<property name="password" value="password" />
</bean>
<bean id="dataSourceMaster"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/pg_master" />
<property name="username" value="usermaster" />
<property name="password" value="password" />
</bean>
</beans>
I use different associations in different database.
Mark the relationship with # transient and just put the id of the entity.
when you will need to refer to the id of the entity at the other database. just use a find
I am going to be confused. I am trying to get Hibernate work with Spring, I can not get rid of a BeanCreationException. Please help me. I am new to Spring (and also Hibernate).
The problem is caused in a controller, having a private attribute userService which is annotated with #Autowired.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.aerts.service.UserService com.aerts.controller.TestController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.aerts.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
I am really confused, please help me somebody.
Here is my root-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<tx:annotation-driven />
<context:component-scan base-package="com.aerts.controller">
</context:component-scan>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:application.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://....."/>
<property name="username" value="....."/>
<property name="password" value="....."/>
<property name="initialSize" value="5"/>
<property name="maxActive" value="20"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Here is my User.java
package com.aerts.domain;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="User")
public class User {
#Id
#GeneratedValue()
#Column(name="id")
int id;
#Column(name="gender")
private Gender gender;
#Column(name="birthdate")
private Date birthdate;
#Column(name="firstname")
private String firstname;
#Column(name="surname")
private String surname;
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public Date getBirthdate() {
return birthdate;
}
public void setBirthdate(Date age) {
this.birthdate = age;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname.trim();
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname.trim();
}
}
My UserDaoImpl:
package com.aerts.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import com.aerts.domain.User;
#Service
public class UserDaoImpl implements UserDao{
#Autowired
private SessionFactory sessionFactory;
#Override
public void addUser(User user) {
sessionFactory.getCurrentSession().save(user);
}
#Override
public List<User> listUser() {
return sessionFactory.getCurrentSession().createQuery("from User")
.list();
}
#Override
public void removeUser(int id) {
User user = (User) sessionFactory.getCurrentSession().get(
User.class, id);
if (user != null) {
sessionFactory.getCurrentSession().delete(user);
}
}
#Override
public void updateUser(User user) {
sessionFactory.getCurrentSession().update(user);
}
}
And my UserServiceImpl:
package com.aerts.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.aerts.dao.UserDao;
import com.aerts.domain.User;
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserDao userDao;
#Override
#Transactional
public void addUser(User user) {
userDao.addUser(user);
}
#Override
#Transactional
public List<User> listUser() {
return userDao.listUser();
}
#Override
#Transactional
public void removeUser(int id) {
userDao.removeUser(id);
}
#Override
#Transactional
public void updateUser(User user) {
userDao.updateUser(user);
}
}
I would really appreciate it if somebody could help me, i am going to be desperate...
Add the service class package to the component-scan base-package list in the application context file
<context:component-scan
base-package="
com.aerts.controller
com.aerts.service">
</context:component-scan>
I'm not expertise in spring but I assume that you have a problem with your service, if you use an interface you should inject ut and not your class...
see this track...
Spring expected at least 1 bean which qualifies as autowire candidate for this dependency