Why do I get UnsatisfiedDependencyException: Error creating bean with name 'routeController' - java

Controller
#RestController
#RequestMapping("/api")
public class RouteController {
#Autowired
RouteServiceImpl routeService;
#GetMapping("/getAllRoutes")
public List<Route> getAllRoutes(){
return routeService.getAll();
}
}
Service
#Service
public class RouteServiceImpl implements RouteService{
#Autowired
RouteRepository routeRepository;
#Override
public Route insert(Route route) {
return routeRepository.save(route);
}
#Override
public Route update(Route route) {
return routeRepository.save(route);
}
#Override
public void delete(int id) {
routeRepository.deleteById(id);
}
#Override
public Route getRouteById(int id) {
return routeRepository.findById(id).get();
}
#Override
public Route getRouteByName(String name) {
return null;
}
#Override
public List<Route> getAll() {
return routeRepository.findAll();
}
}
Repository
#Repository
public interface RouteRepository extends JpaRepository<Route,Integer> {
}

Not linked to your problem, but you should always #Autowire Interfaces and not implementation in your services, also, no need for #Repository on your repo that extends JpaRepository.

Related

Generic DAO cause stack overflow

Hello I Have a problem with my Spring/Hibernate project. I was trying to implement generic classes for DAOs and Services and use one concrete implementation to show something on screen. Everything starts without error, but if i wanna create a new project, after form submisions it throws Stack Overflow error (see image below). I rly cant find out where the problem is. I hope someone here can help me. Below you can see all my code, potentialy can add jsp or config files if necessary. Thanks for your time.
GenericDaoImpl
#SuppressWarnings("unchecked")
#Repository
public abstract class GenericDaoImpl<T, PK extends Serializable> implements IGenericDao<T, PK> {
#Autowired
private SessionFactory sessionFactory;
protected Class<? extends T> entityClass;
public GenericDaoImpl() {
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
entityClass = (Class<? extends T>) pt.getActualTypeArguments()[0];
}
protected Session currentSession() {
return sessionFactory.getCurrentSession();
}
#Override
public PK create(T t) {
return (PK) currentSession().save(t);
}
#Override
public T read(PK id) {
return (T) currentSession().get(entityClass, id);
}
#Override
public void update(T t) {
currentSession().saveOrUpdate(t);
}
#Override
public void delete(T t) {
currentSession().delete(t);
}
#Override
public List<T> getAll() {
return currentSession().createCriteria(entityClass).list();
}
#Override
public void createOrUpdate(T t) {
currentSession().saveOrUpdate(t);
}
GenericServiceImpl
#Service
public abstract class GenericServiceImpl<T, PK extends Serializable> implements IGenericService<T, PK>{
private IGenericDao<T, PK> genericDao;
public GenericServiceImpl(IGenericDao<T,PK> genericDao) {
this.genericDao=genericDao;
}
public GenericServiceImpl() {
}
#Override
#Transactional(propagation = Propagation.REQUIRED)
public PK create(T t) {
return create(t);
}
#Override
#Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public T read(PK id) {
return genericDao.read(id);
}
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void update(T t) {
genericDao.update(t);
}
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void delete(T t) {
genericDao.delete(t);
}
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void createOrUpdate(T t) {
genericDao.createOrUpdate(t);
}
#Override
#Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public List<T> getAll() {
return genericDao.getAll();
}
}
ProjectDaoImpl
#Repository
public class ProjectDaoImpl extends GenericDaoImpl<Project, Integer> implements IProjectDao{
}
ProjectServiceImpl
#Service
public class ProjectServiceImpl extends GenericServiceImpl<Project, Integer> implements IProjectService {
#Autowired
public ProjectServiceImpl(#Qualifier("projectDaoImpl") IGenericDao<Project, Integer> genericDao) {
super(genericDao);
}
}
ProjectController
public class ProjectController {
#Autowired(required = true)
private IProjectService projectService;
#RequestMapping(value = "/projects", method = RequestMethod.GET)
public String listProjects(Model model){
model.addAttribute("project", new Project());
model.addAttribute("listProjects", projectService.getAll());
return "project";
}
//for add and update role both
#RequestMapping(value = "/project/add", method = RequestMethod.POST)
public String addProject(#ModelAttribute("project") Project p){
if( p.getId() == 0){
//new role, add it
projectService.create(p);
} else {
//existing role, call update
projectService.update(p);
}
return "redirect:/projects";
}
#RequestMapping("/remove/{id}")
public String deleteProject(#PathVariable("id") int id){
projectService.delete(projectService.read(id));
return "redirect:/projects";
}
#RequestMapping("edit/{id}")
public String editProject(#PathVariable("id") int id, Model model){
model.addAttribute("project", projectService.read(id));
model.addAttribute("listProjects", projectService.getAll());
return "project";
}
}
#Override
#Transactional(propagation = Propagation.REQUIRED)
public PK create(T t) {
return create(t);
}
This method is calling itself unconditionally. This can only result in a StackOverflowError.
Did you mean to do this?
#Override
#Transactional(propagation = Propagation.REQUIRED)
public PK create(T t) {
return genericDao.create(t);
}

Cannot resolve reference Local ejb-ref

I have an issue in programming an EJB application. I search a solution but I still have the same problem in intelliJ with Glassfish4 :
" Cannot resolve reference [Local ejb-ref name=EJB.AdminEJB,Local 3.x interface =Interface.AdminInterface,ejb-link=null,lookup=,mappedName=,jndi-name=,refType=Session] because there are [2] ejbs in the application with interface Interface.AdminInterface."
And excuse-me for my english, I'm french.
AdminInterface in a package Interface
#Local
public interface AdminInterface {
public void creerParieur(Parieur parieur);
public void supprimerParieur (String login);
public void creerBookmaker(Bookmaker bookmaker);
public void supprimerBookmaker (String login);
public void modifParieur (Parieur parieur);
public void modifBookmaker (Bookmaker bookmaker);
public void ajouterCote(Cote cote);
public void ajouterMatch (Match match);
public List<Cote> listeCote(String log);
public List<Match> listeMatch();
public List<Parieur> listeParieur();
public List<Bookmaker> listeBookmaker();
public Parieur rechercheParieur(String id);
public Bookmaker rechercheBookmaker (String id);
public void setLogin(String login);
public String getLogin();
}
AdminEJB in a package EJB
#Stateless
public class AdminEJB implements AdminInterface{
String login;
String mdp;
#PersistenceContext(unitName = "NewPersistenceUnit")
EntityManager em;
public AdminEJB(){}
public String getLogin(){
return login;
}
public void setLogin(String login){
this.login=login;
}
public String getMdp(){
return mdp;
}
public void setMdp(String mdp){
this.mdp=mdp;
}
public void creerParieur(Parieur parieur){
em.persist(parieur);
}
public void supprimerParieur(String login){
Parieur parieur=new Parieur ();
Query req=em.createQuery("select OBJECT(P) from Parieur P where P.login=:login");
req.setParameter("login", login);
parieur=(Parieur)req.getSingleResult();
em.remove(parieur);
}
public void modifParieur(Parieur parieur){
em.merge(parieur);
}
public List<Parieur> listeParieur(){
Query req=em.createQuery("select OBJECT(P) from Parieur P");
return req.getResultList();
}
public void creerBookmaker(Bookmaker bookmaker){
em.persist(bookmaker);
}
public void supprimerBookmaker(String login){
Bookmaker bookmaker;
Query req=em.createQuery("select OBJECT(B) from Bookmaker B where B.pseudo=:login");
req.setParameter("login", login);
bookmaker=(Bookmaker)req.getSingleResult();
em.remove(bookmaker);
}
public void modifBookmaker(Bookmaker bookmaker){
em.merge(bookmaker);
}
public List<Bookmaker> listeBookmaker(){
Query req=em.createQuery("select OBJECT(B) from Bookmaker B");
return req.getResultList();
}
public List<Match> listeMatch(){
Query req=em.createQuery("select OBJECT(M) from Match M");
return req.getResultList();
}
public Bookmaker rechercheBookmaker(String id){
return em.find(Bookmaker.class,id);
}
public Parieur rechercheParieur(String id){
return em.find(Parieur.class,id);
}
public void ajouterCote (Cote cote){
em.persist(cote);
}
public void ajouterMatch (Match match){
em.persist(match);
}
public List<Cote> listeCote(String log){
Bookmaker bookmaker = new Bookmaker();
bookmaker = this.rechercheBookmaker(log);
Query req = em.createQuery("select OBJECT(C) from Cote C where C.bookmaker=:bookmaker");
req.setParameter("bookmaker", bookmaker);
return req.getResultList();
}
}
ControlerBean in a package ManagedBean
#ManagedBean
#RequestScoped
public class ControlerBean implements Serializable{
Bookmaker bookmaker;
Pari pari;
Parieur parieur;
Match match;
Cote cote;
String nomObjetP;
String nomEnP;
String pseudoUser;
String pwdUser;
#EJB
private AdminInterface admin;
public ControlerBean(){
bookmaker = new Bookmaker();
parieur = new Parieur();
cote = new Cote();
match= new Match();
pari= new Pari();
}
public String getNomObjetP() {
return nomObjetP;
}
public void setNomObjetP(String nomObjetP) {
this.nomObjetP = nomObjetP;
}
public String getNomEnP() {
return nomEnP;
}
public void setNomEnP(String nomEnP) {
this.nomEnP = nomEnP;
}
public Pari getPari() {
return pari;
}
public void setPari(Pari pari){
this.pari=pari;
}
public Bookmaker getBookmaker() {
return bookmaker;
}
public void setBookmaker(Bookmaker bookmaker) {
this.bookmaker = bookmaker;
}
public Parieur getParieur() {
return parieur;
}
public void setParieur(Parieur parieur) {
this.parieur = parieur;
}
public Cote getCote() {
return cote;
}
public void setCote(Cote cote) {
this.cote = cote;
}
public Match getMatch(){
return match;
}
public void setMatch(Match match){
this.match=match;
}
public AdminInterface getAdmin() {
return admin;
}
public void setAdmin(AdminInterface admin) {
this.admin = admin;
}
public String getPseudoUser() { return pseudoUser; }
public void setPseudoUser(String pseudoUser) {
this.pseudoUser = pseudoUser;
}
public String getPwdUser() {
return pwdUser;
}
public void setPwdUser(String pwdUser) {
this.pwdUser = pwdUser;
}
public String addParieur(){
parieur.setArgent(1000);
admin.creerParieur(parieur);
return "OK";
}
public String modifParieur(){
admin.modifParieur(parieur);
return "OK";
}
public String supprParieur(){
admin.supprimerParieur(parieur.getLogin());
return "OK";
}
public String addBookmaker(){
admin.creerBookmaker(bookmaker);
return "OK";
}
public String modifBookmaker(){
admin.modifBookmaker(bookmaker);
return "OK";
}
public String supprBookmaker(){
admin.supprimerBookmaker(bookmaker.getPseudo());
return "OK";
}
public List<Bookmaker> listeBookmaker(){
return admin.listeBookmaker();
}
public List<Parieur> listeParieur(){
return admin.listeParieur();
}
public List<Match> listeMatch(){ return admin.listeMatch(); }
public String addCote(){
pseudoUser = admin.getLogin();
cote.setBookmaker(admin.rechercheBookmaker(pseudoUser));
admin.ajouterCote(cote);
return "OK";
}
public String addMatch(){
admin.ajouterMatch(getMatch());
return "OK";
}
}
Thank's very much for any help
When you have two EJBs implementing the same interface they need to be differentiated so that the container knows which one to inject.
Add the name parameter in the #Stateless annotation to all beans implementing the same interface. In the #EJB annotation, use the beanName parameter to inject the appropriate session bean implementation.
#Stateless(name="AdminEJB1")
public class AdminEJB implements AdminInterface { .... }
#EJB(beanName = "AdminEJB1")
private AdminInterface myAdminEjb;
You can also skip the name parameter in the #Stateless annotation and then use the name of the implementing class as the beanName parameter in the #EJB annotation.
#Stateless
public class AdminEJB implements AdminInterface { .... }
#EJB(beanName = "AdminEJB")
private AdminInterface myAdminEjb;
I had same error, but I didn't work with one interface for different EJBs (generated local Session Beans from entity classes). So I am putting this answer if somebody had same problem as me, as I didn't found one here. My framework generated "ejb-local-ref" tag in pom.xml on its own. After deleting it, all works perfectly.
Another cause for this problem, although uncommon, may be the delay in communicating with the JMX port. To get around this it is possible to put the key -Dhk2.parser.timeout = 300

JAVA Spring : Service returning a null

For some reason, my service is returning a null. The autowires are correct, the service annotation is there, the getters and setters .. But this returns a null :
public PlatformService getPlatformService() {
return platformService;
}
public void setPlatformService(PlatformService platformService) {
this.platformService = platformService;
}
on Debug, it returns platformService = null
Here is my PlatformService :
package empsuite.service;
import java.util.List;
import empsuite.model.Platform;
public interface PlatformService {
public void addPlatform(Platform platform);
public void updatePlatform(Platform platform);
public Platform getPlatformById(int id);
public List<Platform> getPlatform();
}
PlatformServiceImpl :
#Service
#Transactional
public class PlatformServiceImpl implements PlatformService {
#Autowired
PlatformDAO platformDAO;
#Transactional(readOnly = false)
public void addPlatform(Platform platform) {
getPlatformDAO().addPlatform(platform);
}
#Transactional(readOnly = false)
public void updatePlatform(Platform platform) {
getPlatformDAO().updatePlatform(platform);
}
private PlatformDAO getPlatformDAO() {
return platformDAO; }
public void setPlatformDAO(PlatformDAO platformDAO) {
this.platformDAO = platformDAO;
}
public Platform getPlatformById(int id) {
return getPlatformDAO().getPlatformById(id);
}
public List<Platform> getPlatform() {
return getPlatformDAO().getPlatform();
}
}
The DAOImpl function (with sessionfactory autowired) as it is the builder of the HQL :
public List<Platform> getPlatform() {
List list = getSessionFactory().getCurrentSession().createQuery("from Platform").list();
return list;
}
#ManagedProperty is the cause of the problem, so I overriden it and it works with this constructor :
public PlatformManagedBean() {
super();
if(platformService == null){
WebApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
platformService = ctx.getBean(PlatformService.class);
}
}

Hibernate Generic Dao

I want to write abstract class, which will contains all generic methods for working with db like save, update and etc. After that create as many implementations as many DAO's I need, and, if needed, overwrite/add methods.
public interface Dao<T, ID extends Serializable> {
void save(T t);
T get(ID id);
void update(T t);
void remove(T t);
List<T> findAll();
}
#Repository
#Transactional
public abstract class AbstractDao<T, ID extends Serializable> implements Dao<T, ID> {
#Autowired
private SessionFactory sessionFactory;
private Class<T> clazz;
public AbstractDao(Class<T> clazz) {
this.clazz = clazz;
}
public void save(T t) {
sessionFactory.getCurrentSession().save(t);
}
public T get(ID id) {
return sessionFactory.getCurrentSession().get(clazz, id);
}
public void update(T t) {
sessionFactory.getCurrentSession().update(t);
}
public void remove(T t) {
sessionFactory.getCurrentSession().delete(t);
}
public List<T> findAll() {
return sessionFactory.getCurrentSession().createCriteria(clazz).list();
}
}
#Repository
#Transactional
public class UserDao extends AbstractDao<User, Integer> {
public UserDao() {
super(User.class);
}
}
public class MainTest {
#Test
public void testName() throws Exception {
ApplicationContext ctx = new AnnotationConfigApplicationContext(HibernateConfig.class);
UserDao userDao = ctx.getBean(UserDao.class);
...
}
}
And I get this error:
No qualifying bean of type [com.sevak-avet.UserDao] is defined
If I don't use AbstractDao class and implement all methods directly in UserDao, it works. What I'm doing wrong?

Hibernate's SessionFactory in each DAO or only in the extended class?

I run in few huge problems by using getSession() on HibernateDaoSupport and now when i try to fix it I was wondering if it is right to make a abstract class like this bellow and make all Dao's to extend it instead of adding SessionFactory in each Dao ?
If it is, then would creating bean of this abstract Dao class and passing it the session factory then work once other Dao's extend it? Or that is not even possible?
public abstract class AbstractDAOImpl<T> implements
AbstractDAO<T> {
private static Logger _logger = LoggerFactory
.getLogger(AbstractDAOImpl.class);
private SessionFactory factory;
#Override
public void refresh(final T object) {
try {
factory.getCurrentSession().refresh(object);
} catch (Exception e) {
_logger.error("Cannot refresh object " + object, e);
}
}
#Override
public void remove(final T object) {
try {
factory.getCurrentSession().delete(object);
} catch (Exception e) {
_logger.error("Cannot remove object " + object, e);
}
}
#Override
public void save(final T object) {
try {
factory.getCurrentSession().saveOrUpdate(object);
} catch (Exception e) {
_logger.error("Cannot save or update object " + object, e);
}
}
}
public interface RootDAO<T> extends Serializable {
public List<T> loadAll();
public T save(T entity);
public void delete(T entity);
public void markAsDeleted(T entity);
public T get(Serializable id);
public T load(Serializable id);
public void saveOrUpdate(T entity);
public void deleteAll(Collection<T> entities);
public void saveOrUpdateAll(Collection<T> entities);
public List<T> find(String hql);
public void update(T entity);
public T getByExampleUnique(T entity);
public List<T> getByExampleList(T entity);
public List<T> listAll();
public Object execute(HibernateCallback action);
public List<T> findByNamedParam(String queryString, String paramName,Object value);
public List<T> findByNamedParam(String queryString, String[] paramNames,Object[] values);
.
.
.
.
}
#Component
public abstract class RootDAOImpl<T> extends HibernateDaoSupport implements RootDAO<T> {
protected Logger logger = LoggerFactory.getLogger(getClass());
private Class<T> clazz;
#Autowired
public void init(SessionFactory factory) {
setSessionFactory(factory);
}
public RootDAOImpl(Class<T> clazz) {
this.clazz = clazz;
}
public void delete(T entity) {
getHibernateTemplate().delete(entity);
}
public void delete(String id) {
getHibernateTemplate().delete(new FbUser(id));
}
public void markAsDeleted(T entity) {
// Mark entity as deleted
try {
Method setDeletedMethod = clazz.getDeclaredMethod("setDeleted", Boolean.class);
setDeletedMethod.invoke(entity, true);
getHibernateTemplate().saveOrUpdate(entity);
} catch (Exception e) {
e.printStackTrace();
}
// actually delete
// getHibernateTemplate().delete(entity);
}
#Override
public void deleteAll(Collection<T> entities) {
getHibernateTemplate().deleteAll(entities);
}
#Override
public void saveOrUpdateAll(Collection<T> entities) {
getHibernateTemplate().saveOrUpdateAll(entities);
}
#SuppressWarnings("unchecked")
#Override
public T get(Serializable id) {
return (T) getHibernateTemplate().get(clazz, id);
}
#SuppressWarnings("unchecked")
#Override
public T load(Serializable id) {
return (T) getHibernateTemplate().load(clazz, id);
}
#SuppressWarnings("unchecked")
#Override
public List<T> find(String hql) {
return (List<T>) getHibernateTemplate().find(hql);
}
#Override
public Object execute(HibernateCallback action) {
return getHibernateTemplate().execute(action);
}
.
.
.
}
#Repository
public class UserDAOImpl extends RootDAOImpl<User> implements UserDAO{
public UserDAOImpl() {
super(User.class);
}
}
If you are not using a DI framework you may need to keep a reference for SessionFactory and pass it yourself when you create the DAO instance.
This is exactly why people use JPA implementation by hibernate. You just need to start using the JPA's EntityManager which leverages on SessionFactory by itself in the best possible design patterns. You dont have to reinvent the whole design patterns here. All you need to do is just use CRUD operations of EntityManager in each of your DAO as shown in the following example. All the best with your implementation.
http://www.myhomepageindia.com/index.php/2009/04/02/jpa-hibernate-with-oracle-on-eclipse.html

Categories