IllegalArgumentException occurred calling getter - java

Hi every body while i'm tring to create my first project with spring mvc and Hibernate
I'm working with eclipse and maven Jboss tools
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.orm.hibernate4.HibernateSystemException: IllegalArgumentException occurred calling getter of com.gestEtu.project.model.bo.Etudiant.idEtudiant; nested exception is org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of com.gestEtu.project.model.bo.Etudiant.idEtudiant
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
Etudiant Class Code is :
package com.gestEtu.project.model.bo;
import java.util.HashSet;
import java.util.Set;
public class Etudiant implements java.io.Serializable {
private Integer idEtudiant;
private Groupe groupe;
private Utilisateur utilisateur;
private Long cne;
private String filiere;
private Set<Fichelecture> fichelectures = new HashSet();
public Etudiant() {
}
public Etudiant(Integer idEtudiant) {
this.idEtudiant = idEtudiant;
}
public Etudiant(Integer idEtudiant, Groupe groupe, Utilisateur utilisateur,
Long cne, String filiere, Set<Fichelecture> fichelectures) {
this.idEtudiant = idEtudiant;
this.groupe = groupe;
this.utilisateur = utilisateur;
this.cne = cne;
this.filiere = filiere;
this.fichelectures = fichelectures;
}
public Integer getIdEtudiant() {
return idEtudiant;
}
public void setIdEtudiant(Integer idEtudiant) {
this.idEtudiant = idEtudiant;
}
public Groupe getGroupe() {
return groupe;
}
public void setGroupe(Groupe groupe) {
this.groupe = groupe;
}
public Utilisateur getUtilisateur() {
return utilisateur;
}
public void setUtilisateur(Utilisateur utilisateur) {
this.utilisateur = utilisateur;
}
public Long getCne() {
return cne;
}
public void setCne(Long cne) {
this.cne = cne;
}
public String getFiliere() {
return filiere;
}
public void setFiliere(String filiere) {
this.filiere = filiere;
}
public Set<Fichelecture> getFichelectures() {
return fichelectures;
}
public void setFichelectures(Set<Fichelecture> fichelectures) {
this.fichelectures = fichelectures;
}
public Compte getCompte(){
return this.utilisateur.getCompte();
}
public void setCompte(Compte Compte){
this.utilisateur.setCompte(Compte);
}
}
the DAO Class code is :
package com.gestEtu.project.model.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.gestEtu.project.model.bo.Etudiant;
#Repository
#Transactional
public class EtudiantDAOHib extends HibernateDaoSupport implements EtudiantDAO {
#Autowired
public EtudiantDAOHib(SessionFactory sessionFactory) {
setSessionFactory(sessionFactory);
}
#Override
public void ajouterEtudiant(Etudiant etudiant) {
getHibernateTemplate().saveOrUpdate(etudiant);
}
#Override
public Etudiant findEtudiantByCne(int cne) {
return (Etudiant) getHibernateTemplate().find("from Etudiant e where e.cne=?", cne);
}
#Override
public List<Etudiant> listeEtudiant() {
return (List<Etudiant>)(Object) getHibernateTemplate().find("from Etudiant");
}
#Override
public void modifierEtudiant(Etudiant etudiant) {
getHibernateTemplate().saveOrUpdate(etudiant);
}
#Override
public void suprimerEtudiant(int idEtudiant) {
getHibernateTemplate().delete("from Etudiant e where e.idEtudiant=?", idEtudiant);
}
}
the Etudiant Service Class code is :
package com.gestEtu.project.model.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.gestEtu.project.model.bo.Etudiant;
import com.gestEtu.project.model.dao.EtudiantDAO;
#Service
#Transactional
public class EtudiantServiceImp implements EtudiantService {
private final EtudiantDAO etudiantDAO;
#Autowired
public EtudiantServiceImp(EtudiantDAO etudiantDAO) {
this.etudiantDAO = etudiantDAO;
}
#Override
public void ajouterEtudiant(Etudiant etudiant) {
etudiantDAO.ajouterEtudiant(etudiant);
}
#Override
public Etudiant findEtudiantByCne(int cne) {
return etudiantDAO.findEtudiantByCne(cne);
}
#Override
public List<Etudiant> listeEtudiant() {
return etudiantDAO.listeEtudiant();
}
#Override
public void modifierEtudiant(Etudiant etudiant) {
etudiantDAO.modifierEtudiant(etudiant);
}
#Override
public void suprimerEtudiant(int idEtudiant) {
}
}

Related

How I can to validate my Junit test with Gson parse

I'm using the Gson library and jakarta. Although I have been able to use the conversion in CarrinhoResource.java as below, my ClienteTest.java cannot use the String content (already in json) inside the cart. I cant run my test a just only message into my intellij is (Cannot resolve method 'fromJson(java.lang.String)').
Can someone help me?
Class CarrinhoResource.java
package br.com.alura.loja.resource;
import br.com.alura.loja.dao.CarrinhoDAO;
import br.com.alura.loja.modelo.Carrinho;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
#Path("/v1/carrinhos")
public class CarrinhoResource {
#GET
#Produces(MediaType.APPLICATION_JSON)
public String busca(){
Carrinho carrinho = new CarrinhoDAO().busca(1L);
return carrinho.toJson();
}
}
Carrinho.java
package br.com.alura.loja.modelo;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.google.gson.Gson;
public class Carrinho {
private List<Produto> produtos = new ArrayList<Produto>();
private String rua;
private String cidade;
private long id;
public Carrinho adiciona(Produto produto) {
produtos.add(produto);
return this;
}
public Carrinho para(String rua, String cidade) {
this.rua = rua;
this.cidade = cidade;
return this;
}
public Carrinho setId(long id) {
this.id = id;
return this;
}
public String getRua() {
return rua;
}
public void setRua(String rua) {
this.rua = rua;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public long getId() {
return id;
}
public void remove(long id) {
for (Iterator iterator = produtos.iterator(); iterator.hasNext();) {
Produto produto = (Produto) iterator.next();
if(produto.getId() == id) {
iterator.remove();
}
}
}
public void troca(Produto produto) {
remove(produto.getId());
adiciona(produto);
}
public void trocaQuantidade(Produto produto) {
for (Iterator iterator = produtos.iterator(); iterator.hasNext();) {
Produto p = (Produto) iterator.next();
if(p.getId() == produto.getId()) {
p.setQuantidade(produto.getQuantidade());
return;
}
}
}
public List<Produto> getProdutos() {
return produtos;
}
public String toJson() {
return new Gson().toJson(this);
}
}
ClienteTest.java
package br.com.alura.loja;
import br.com.alura.loja.modelo.Carrinho;
import com.google.gson.*;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.WebTarget;
import org.junit.Assert;
import org.junit.Test;
public class ClienteTest {
#Test
public void testaConexaoServidor() {
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8085");
String conteudo = target.path("/v1/carrinhos").request().get(String.class);
Carrinho carrinho = (Carrinho) new Gson().fromJson(conteudo); **//Cannot resolve method 'fromJson(java.lang.String)'/**
System.out.println(carrinho);
Assert.assertEquals("Rua Vergueiro, 3185", carrinho.getRua());
}
}
Carrinho carrinho = (Carrinho) new Gson().fromJson(conteudo); **//Cannot resolve method 'fromJson(java.lang.String)'/**
The reason for this is that there is no Gson.fromJson(String) method, see the Gson class documentation. For deserialization Gson needs to know which type you are expecting, so all fromJson methods have a second parameter representing the type.
You can simply change your code to:
Carrinho carrinho = new Gson().fromJson(conteudo, Carrinho.class);

Why can't the database still not save the data with my current TypeConverter?

I am stuck with implementing a TypeConverter to my Database. I have added the TypeConverters but it still keeps saying that it cannot figure out how to save the field into the database. Or maybe I have missed something? I was following this article to create TypeConverters (https://android.jlelse.eu/room-persistence-library-typeconverters-and-database-migration-3a7d68837d6c), which is with my knowledge so far a bit hard to understand.
Any help would be appreciated!
MyGame.java:
package com.riceplant.capstoneproject.room;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;
import com.riceplant.capstoneproject.data.Cover;
import com.riceplant.capstoneproject.data.Genre;
import com.riceplant.capstoneproject.data.Platform;
import com.riceplant.capstoneproject.data.ReleaseDate;
import com.riceplant.capstoneproject.data.Video;
import java.util.List;
#Entity(tableName = "game")
public class MyGame {
#PrimaryKey(autoGenerate = true)
private Integer mId;
private Cover mCover;
private String mName;
private Double mPopularity;
private String mSummary;
private List<Genre> mGenres;
private List<Platform> mPlatform;
private Double mRating;
private List<ReleaseDate> mReleaseDate;
private List<Video> mVideos;
#Ignore
public MyGame() {
}
public MyGame(Integer id,
Cover cover,
String name,
Double popularity,
String summary,
List<Genre> genres,
List<Platform> platform,
Double rating,
List<ReleaseDate> releaseDate,
List<Video> videos) {
mId = id;
mCover = cover;
mName = name;
mPopularity = popularity;
mSummary = summary;
mGenres = genres;
mPlatform = platform;
mRating = rating;
mReleaseDate = releaseDate;
mVideos = videos;
}
public Integer getId() {
return mId;
}
public void setId(Integer id) {
id = mId;
}
public Cover getCover() {
return mCover;
}
public void setCover(Cover cover) {
cover = mCover;
}
public String getName() {
return mName;
}
public void setName(String name) {
name = mName;
}
public Double getPopularity() {
return mPopularity;
}
public void setPopularity(Double popularity) {
popularity = mPopularity;
}
public String getSummary() {
return mSummary;
}
public void setSummary(String summary) {
summary = mSummary;
}
public List<Genre> getGenres() {
return mGenres;
}
public void setGenres(List<Genre> genres) {
genres = mGenres;
}
public List<Platform> getPlatform() {
return mPlatform;
}
public void setPlatform(List<Platform> platform) {
platform = mPlatform;
}
public Double getRating() {
return mRating;
}
public void setRating(Double rating) {
rating = mRating;
}
public List<ReleaseDate> getReleaseDate() {
return mReleaseDate;
}
public void setReleaseDate(List<ReleaseDate> releaseDate) {
releaseDate = mReleaseDate;
}
public List<Video> getVideos() {
return mVideos;
}
public void setVideos(List<Video> videos) {
videos = mVideos;
}
}
Converters.java
package com.riceplant.capstoneproject.room;
import androidx.room.TypeConverter;
import com.riceplant.capstoneproject.data.Cover;
import com.riceplant.capstoneproject.data.Genre;
import com.riceplant.capstoneproject.data.Platform;
import com.riceplant.capstoneproject.data.Video;
public class Converters {
#TypeConverter
public static Cover toCover(String value) {
return value == null ? null : new Cover();
}
#TypeConverter
public static String toString(Cover value) {
return value == null ? null : value.getUrl();
}
#TypeConverter
public static Genre toGenre(String value) {
return value == null ? null : new Genre();
}
#TypeConverter
public static String toString(Genre value) {
return value == null ? null : value.getName();
}
#TypeConverter
public static Platform toPlatform(String value) {
return value == null ? null : new Platform();
}
#TypeConverter
public static String toString(Platform value) {
return value == null ? null : value.getName();
}
#TypeConverter
public static Video toString(String value) {
return value == null ? null : new Video();
}
#TypeConverter
public static String toVideo(Video value) {
return value == null ? null : value.getVideoId();
}
}
GameRoomDatabase.java
package com.riceplant.capstoneproject.room;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.TypeConverters;
#Database(entities = {MyGame.class}, version = 3, exportSchema = false)
#TypeConverters({Converters.class})
public abstract class GameRoomDatabase extends RoomDatabase {
private static final String LOG_TAG = GameRoomDatabase.class.getSimpleName();
private static final Object LOCK = new Object();
private static final String DATABASE_NAME = "gameslist";
private static GameRoomDatabase sInstance;
public static GameRoomDatabase getInstance(Context context) {
if (sInstance == null) {
synchronized (LOCK) {
sInstance = Room.databaseBuilder(context.getApplicationContext(),
GameRoomDatabase.class, GameRoomDatabase.DATABASE_NAME)
.fallbackToDestructiveMigration()
.build();
}
}
return sInstance;
}
public abstract GameDao gameDao();
}
GameDao.java
package com.riceplant.capstoneproject.room;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
#Dao
public interface GameDao {
#Query("SELECT * FROM game ORDER BY mId")
LiveData<List<MyGame>> loadAllGames();
#Insert
void insertGame(MyGame myGame);
#Update(onConflict = OnConflictStrategy.REPLACE)
void updateGame(MyGame myGame);
#Delete
void deleteGame(MyGame myGame);
#Query("SELECT * FROM game WHERE mId = :id")
MyGame loadGameById(int id);
}
GameViewModel
package com.riceplant.capstoneproject.room;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import java.util.List;
public class GameViewModel extends AndroidViewModel {
private LiveData<List<MyGame>> games;
public GameViewModel(#NonNull Application application) {
super(application);
GameRoomDatabase database = GameRoomDatabase.getInstance(this.getApplication());
games = database.gameDao().loadAllGames();
}
public LiveData<List<MyGame>> getGames() {
return games;
}
}
Your DB contains Lists of Genre, Platform, ReleaseDate and Video. SQLite supports column types of INTEGER, REAL, TEXT and BLOB. You must provide methods for conversion of your List types to/from String(TEXT) or one of the other supported SQLite types.
For example:
#TypeConverter
public static List<Genre> toGenreList(String value) {
// TODO conversion code
}
#TypeConverter
public static String toString(List<Genre> value) {
// TODO conversion code
}

java.util.LinkedHashMap cannot be cast to com.common.pojo.myDataDetails

My java class is throwing some error. In my class i am using this to get my data.
((myDataDetails) Names.get(0)).InputParamNames().add("SomeValue");
But it is throwing error
Here is my Pohjo Class.
package common.pojo;
import java.util.Date;
import java.util.List;
public class myDataDetails
{
private String myID;
private List<String> InputParamNames;
private List InputParamData;
public String getmyID() {
return this.myID;
}
public void setmyID(String myID) {
this.myID = myID;
}
public List<String> getInputParamNames() {
return this.InputParamNames;
}
public void setInputParamNames(List<String> InputParamNames) {
this.InputParamNames = InputParamNames;
}
public List getInputParamData() {
return this.InputParamData;
}
public void setInputParamData(List InputParamData) {
this.InputParamData = InputParamData;
}
}
What should I need to change in pojo to avoid this exception.
Your class 'myDataDetails' needs to extend from LinkedHashMap in order to cast it.
What you have right now is a regular POJO class that is not an instance of LinkedHashMap, so you can't cast it as such.
EDIT: It should look like this
package common.pojo;
import java.util.Date;
import java.util.List;
import java.util.LinkedHashMap;
public class myDataDetails extends LinkedHashMap<Object, Object>
{
private String myID;
private List<String> InputParamNames;
private List InputParamData;
public String getmyID() {
return this.myID;
}
public void setmyID(String myID) {
this.myID = myID;
}
public List<String> getInputParamNames() {
return this.InputParamNames;
}
public void setInputParamNames(List<String> InputParamNames) {
this.InputParamNames = InputParamNames;
}
public List getInputParamData() {
return this.InputParamData;
}
public void setInputParamData(List InputParamData) {
this.InputParamData = InputParamData;
}
}

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

Table is not mapped ejb3.0

Hello i use EJB 3 and i'm trying to get a simple list from DB but i find this message" travauxdereseauurbain is not mapped [select Tr from travauxdereseauurbain Tr]" and i don't really get what does it means
Here is the entity
package com.pfe.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.soap.Text;
#Entity
#Table(name="travauxdereseauurbain")
public class Traveauxdereseauurbain implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="idtru")
private int idtru;
#Column(name = "article")
private String article;
#Column (name="designationtraveau")
private String designationtraveau;
#Column(name="unite")
private String unite;
#Column(name="prixHTVA")
private float prixHTVA;
#Column(name="prixTTC")
private float prixTTC;
#Column (name="qtt")
private float qtt;
#Column(name="montantHTVA")
private float montantHTVA;
#Column(name="montantTTC")
private float montantTTC;
public int getIdtru() {
return idtru;
}
public void setIdtru(int idtru) {
this.idtru = idtru;
}
public String getArticle() {
return article;
}
public void setArticle(String article) {
this.article = article;
}
public String getDesignationtraveau() {
return designationtraveau;
}
public void setDesignationtraveau(String designationtraveau) {
this.designationtraveau = designationtraveau;
}
public String getUnite() {
return unite;
}
public void setUnite(String unite) {
this.unite = unite;
}
public float getPrixHTVA() {
return prixHTVA;
}
public void setPrixHTVA(float prixHTVA) {
this.prixHTVA = prixHTVA;
}
public float getPrixTTC() {
return prixTTC;
}
public void setPrixTTC(float prixTTC) {
this.prixTTC = prixTTC;
}
public float getQtt() {
return qtt;
}
public void setQtt(float qtt) {
this.qtt = qtt;
}
public float getMontantHTVA() {
return montantHTVA;
}
public void setMontantHTVA(float montantHTVA) {
this.montantHTVA = montantHTVA;
}
public float getMontantTTC() {
return montantTTC;
}
public void setMontantTTC(float montantTTC) {
this.montantTTC = montantTTC;
}
public Traveauxdereseauurbain(int idtru, String article,
String designationtraveau, String unite, float prixHTVA, float prixTTC,
float qtt, float montantHTVA, float montantTTC) {
super();
this.idtru = idtru;
this.article = article;
this.designationtraveau = designationtraveau;
this.unite = unite;
this.prixHTVA = prixHTVA;
this.prixTTC = prixTTC;
this.qtt = qtt;
this.montantHTVA = montantHTVA;
this.montantTTC = montantTTC;
}
public Traveauxdereseauurbain() {
super();
}
}
`
and the DAO class
package com.pfe.data;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import com.pfe.controller.travauxdereseauurbainBean;
import com.pfe.model.Traveauxdereseauurbain;
import com.pfe.model.Traveauxdereseauurbain;
#Stateless
public class TravauxdereseauurbainDAO {
#PersistenceContext
private EntityManager em;
public void AddTravauxdereseauurbainDAO (Traveauxdereseauurbain Trurbain)
{
em.persist(Trurbain);
}
public Traveauxdereseauurbain affichernimpr()
{
Query q =em.createNamedQuery("select tr from travauxdereseauurbain tr");
return (Traveauxdereseauurbain) q.getResultList().get(0);
}
}
`
and i got this error:
Caused by: javax.ejb.EJBException:
java.lang.IllegalArgumentException:
org.hibernate.hql.internal.ast.QuerySyntaxException:
travauxdereseauurbain is not mapped [select Tr from
travauxdereseauurbain Tr]
use createQuery instead of createNamedQuery..
There is a difference between those two..
A named query must be defined on the entity before being referenced by an entity managers. This might explain it in more details: http://www.objectdb.com/java/jpa/query/named

Categories