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
Related
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
}
I'm getting into a hibernate error when I run a query that returns all the BD elements of type MessageUser.
I am mapping a binary tree and the MessageUser class contains a copy of this tree.
I mapped the tree with de objects children and a parent object and I mapped the two children with the same father, I suppose this is the error but I don't know an alternative way to have a similar but working solution.
This is my code
AbstractNode.java
/**
* This code is under license Creative Commons Attribution-ShareAlike 1.0
*
*/
package it.unibas.codinghuffman.model.logic.composit;
import it.unibas.codinghuffman.model.MessageUser;
import it.unibas.codinghuffman.model.logic.visitor.IVisitor;
import java.util.Objects;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.OneToOne;
import javax.persistence.Transient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* #author Vincenzo Palazzo
*/
#Entity(name = "abstract_node")
#Inheritance(strategy = InheritanceType.JOINED)
public class AbstractNode implements INode, Comparable<AbstractNode> {
private static final Log LOGGER = LogFactory.getLog(AbstractNode.class);
protected String value;
protected int frequency;
protected int valueArch;
private AbstractNode leaftNode;
private AbstractNode rightNode;
//for hibernate
private Long id;
private MessageUser message;
private AbstractNode father;
public AbstractNode(AbstractNode leaftNode, AbstractNode rightNode) {
this.leaftNode = leaftNode;
this.rightNode = rightNode;
this.leaftNode.setFather(this);
this.leaftNode.setValueArch(0);
this.rightNode.setFather(this);
this.rightNode.setValueArch(1);
if (this.leaftNode.getFather() == null) {
throw new IllegalArgumentException("Fater null");
}
if (this.rightNode.getFather() == null) {
throw new IllegalArgumentException("Fater null");
}
}
public AbstractNode() {
}
#Transient
public boolean isLeaft() {
return leaftNode == null;
}
#OneToOne(mappedBy = "father", cascade = CascadeType.ALL)
public AbstractNode getLeaftNode() {
return leaftNode;
}
public void setLeaftNode(AbstractNode leaftNode) {
this.leaftNode = leaftNode;
this.leaftNode.setFather(this);
this.leaftNode.setValueArch(0);
}
#OneToOne(mappedBy = "father", cascade = CascadeType.ALL)
public AbstractNode getRightNode() {
return rightNode;
}
public void setRightNode(AbstractNode rightNode) {
this.rightNode = rightNode;
this.rightNode.setFather(this);
this.rightNode.setValueArch(1);
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public int getFrequency() {
return frequency;
}
public void setFrequency(int frequency) {
this.frequency = frequency;
}
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#OneToOne
public MessageUser getMessage() {
return message;
}
public void setMessage(MessageUser message) {
this.message = message;
}
#OneToOne
public AbstractNode getFather() {
return father;
}
public void setFather(AbstractNode father) {
this.father = father;
}
public int getValueArch() {
return valueArch;
}
public void setValueArch(int valueArch) {
this.valueArch = valueArch;
}
public void accept(IVisitor visitor) {
if (visitor == null) {
LOGGER.error("The visitor into method accept is null");
throw new IllegalArgumentException("The visitor into method accept is null");
}
}
#Override
public int hashCode() {
int hash = 7;
hash = 83 * hash + Objects.hashCode(this.value);
hash = 83 * hash + Objects.hashCode(this.leaftNode);
hash = 83 * hash + Objects.hashCode(this.rightNode);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final AbstractNode other = (AbstractNode) obj;
if (!Objects.equals(this.value, other.value)) {
return false;
}
if (!Objects.equals(this.leaftNode, other.leaftNode)) {
return false;
}
if (!Objects.equals(this.rightNode, other.rightNode)) {
return false;
}
return true;
}
#Override
public int compareTo(AbstractNode o) {
return ((Integer) frequency).compareTo(o.getFrequency());
}
}
NodeComplex.java
/**
* This code is under license Creative Commons Attribution-ShareAlike 1.0
*
*/
package it.unibas.codinghuffman.model.logic.composit;
import it.unibas.codinghuffman.model.logic.visitor.IVisitor;
import javax.persistence.Entity;
/**
*
* #author Vincenzo Palazzo
*/
#Entity(name = "complex_node")
public class NodeComplex extends AbstractNode{
public NodeComplex(String value, int frequency, AbstractNode leaftNode, AbstractNode rightNode) {
super(leaftNode, rightNode);
this.value = value;
this.frequency = frequency;
}
public NodeComplex() {
super();
//throw new IllegalArgumentException("You are creating a lefth node, please you use the NodeLeaft implementation");
}
#Override
public void accept(IVisitor visitor) {
super.accept(visitor);
visitor.visitComplexNode(this);
}
}
NodeLeaft.class
/**
* This code is under license Creative Commons Attribution-ShareAlike 1.0
*
*/
package it.unibas.codinghuffman.model.logic.composit;
import it.unibas.codinghuffman.model.logic.visitor.IVisitor;
import javax.persistence.Entity;
/**
*
* #author Vincenzo Palazzo
*/
#Entity(name = "leafth_node")
public class NodeLeaft extends AbstractNode {
public NodeLeaft(AbstractNode leaftNode, AbstractNode rightNode) {
throw new IllegalArgumentException("You are creating a complex node, please you use the NodeComplex implementation");
}
public NodeLeaft(String value, int frequency) {
super();
this.value = value;
this.frequency = frequency;
}
public NodeLeaft() {
super();
}
#Override
public void accept(IVisitor visitor) {
super.accept(visitor);
visitor.visitLeaftNode(this);
}
#Override
public String toString() {
return value + frequency;
}
}
MessageUser.class
/*
* This code is under license Creative Commons Attribution-ShareAlike 1.0
*
*/
package it.unibas.codinghuffman.model;
import it.unibas.codinghuffman.model.logic.composit.AbstractNode;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
/**
*
* #author https://github.com/vincenzopalazzo
*/
#Entity(name = "messages")
public class MessageUser {
private Long id;
private String word;
private int lenghtAsci;
private int lenghtHuffman;
private int ratioCompression;
//This is not request to app
private AbstractNode huffmanTree;
private String huffmanCoding;
private String stringHuffmanTree;
public MessageUser() {}
public MessageUser(String word, int lenghtAsci, int lenghtHuffman, int ratioCompression) {
this.word = word;
this.lenghtAsci = lenghtAsci;
this.lenghtHuffman = lenghtHuffman;
this.ratioCompression = ratioCompression;
}
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
// #Column(nullable = false)
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
//#Column(nullable = false)
public int getLenghtAsci() {
return lenghtAsci;
}
public void setLenghtAsci(int lenghtAsci) {
this.lenghtAsci = lenghtAsci;
}
// #Column(nullable = false)
public int getLenghtHuffman() {
return lenghtHuffman;
}
public void setLenghtHuffman(int lenghtHuffman) {
this.lenghtHuffman = lenghtHuffman;
}
// #Column(nullable = false)
public int getRatioCompression() {
return ratioCompression;
}
public void setRatioCompression(int ratioCompression) {
this.ratioCompression = ratioCompression;
}
#OneToOne(mappedBy = "message", cascade = CascadeType.ALL)
public AbstractNode getHuffmanTree() {
return huffmanTree;
}
public void setHuffmanTree(AbstractNode huffmanTree) {
this.huffmanTree = huffmanTree;
huffmanTree.setMessage(this);
}
public String getHuffmanCoding() {
return huffmanCoding;
}
public void setHuffmanCoding(String huffmanCoding) {
this.huffmanCoding = huffmanCoding;
}
public String getStringHuffmanTree() {
return stringHuffmanTree;
}
public void setStringHuffmanTree(String stringHuffmanTree) {
this.stringHuffmanTree = stringHuffmanTree;
}
}
Exception generater
Caused by: org.hibernate.PropertyAccessException: Exception occurred inside setter of it.unibas.codinghuffman.model.logic.composit.AbstractNode.leaftNode
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:91)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.setPropertyValues(AbstractEntityTuplizer.java:713)
at org.hibernate.tuple.entity.PojoEntityTuplizer.setPropertyValues(PojoEntityTuplizer.java:362)
at org.hibernate.persister.entity.AbstractEntityPersister.setPropertyValues(AbstractEntityPersister.java:4718)
at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:188)
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:144)
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1115)
at org.hibernate.loader.Loader.processResultSet(Loader.java:973)
at org.hibernate.loader.Loader.doQuery(Loader.java:921)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:325)
at org.hibernate.loader.Loader.loadEntity(Loader.java:2149)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:78)
at org.hibernate.loader.entity.EntityLoader.loadByUniqueKey(EntityLoader.java:161)
at org.hibernate.persister.entity.AbstractEntityPersister.loadByUniqueKey(AbstractEntityPersister.java:2385)
at org.hibernate.type.EntityType.loadByUniqueKey(EntityType.java:767)
at org.hibernate.type.EntityType.resolve(EntityType.java:505)
at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:170)
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:144)
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1115)
at org.hibernate.loader.Loader.processResultSet(Loader.java:973)
at org.hibernate.loader.Loader.doQuery(Loader.java:921)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:325)
at org.hibernate.loader.Loader.loadEntity(Loader.java:2149)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:78)
at org.hibernate.loader.entity.EntityLoader.loadByUniqueKey(EntityLoader.java:161)
at org.hibernate.persister.entity.AbstractEntityPersister.loadByUniqueKey(AbstractEntityPersister.java:2385)
at org.hibernate.type.EntityType.loadByUniqueKey(EntityType.java:767)
at org.hibernate.type.EntityType.resolve(EntityType.java:505)
at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:170)
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:144)
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1115)
at org.hibernate.loader.Loader.processResultSet(Loader.java:973)
at org.hibernate.loader.Loader.doQuery(Loader.java:921)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355)
at org.hibernate.loader.Loader.doList(Loader.java:2554)
at org.hibernate.loader.Loader.doList(Loader.java:2540)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2370)
at org.hibernate.loader.Loader.list(Loader.java:2365)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:126)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1718)
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:380)
at it.unibas.codinghuffman.persistence.hibernate.DAOGenericoHibernate.findByCriteria(DAOGenericoHibernate.java:105)
... 47 more
Caused by: java.lang.reflect.InvocationTargetException
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.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:68)
... 90 more
Caused by: java.lang.NullPointerException
at it.unibas.codinghuffman.model.logic.composit.AbstractNode.setLeaftNode(AbstractNode.java:78)
I want to give at this question an answer, the exception generate from hibernate is generated because hibernate fin two objects with the same id, for resolving this but I must add another information to the children of the configuration and this configuration is this JoinColum("fater_id")
The mapping for the children is this
#OneToOne(mappedBy = "father", cascade = CascadeType.ALL)
#JoinColum("fater_id")
public AbstractNode getLeaftNode() {
return leaftNode;
}
#OneToOne(mappedBy = "father", cascade = CascadeType.ALL)
#JoinColum("fater_id")
public AbstractNode getRightNode() {
return rightNode;
}
I am newbie to spring and java,
I have a case, where i am trying to fetching rows from the mysql table
This is my Controller:
#RequestMapping(value = "/pharmacy/order/dates", method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
public PharmacyOrderDateResponse orderDates(#Valid #RequestBody PharmacyOrderDateRequest request) {
List<PrescriptionOrder> pharmacyOrders = prescriptionOrderService.orderDatesByPharmacyId(request.getPharmacyId(), request.getOrderStatus(), true);
if(pharmacyOrders.size() == 0) {
throw new EntityNotFoundException("No pharmacy orders found");
}
PharmacyOrderDateResponse response = new PharmacyOrderDateResponse();
Set<Date> orderDateSet = new HashSet<>();
for(PrescriptionOrder pharmacyOrder : pharmacyOrders) {
//orderDateSet.add(longToDate(pharmacyOrder.getCreatedAt().getTime()));
}
response.setPharmacyId(pharmacyOrders.get(0).getPharmacyId());
response.setStatus(ResponseStatusCode.SUCCESS);
response.setPharmacyOrderDateDetails(orderDateSet);
response.setTotalDates(orderDateSet.size());
return response;
}
The above controller is used to call the service by the function, so that to get the list of prescription orders.
This is my Service:
package com.axonytes.corporate.service;
import java.util.Date;
import java.util.List;
import com.axonytes.corporate.entity.PrescriptionOrder;
public interface PrescriptionOrderService {
List<PrescriptionOrder> orderDatesByPharmacyId(Long labId, String orderStatus, Boolean status);
}
This is my ServiceImpl:
#Service
#Transactional(readOnly = true)
public class PrescriptionOrderServiceImpl implements PrescriptionOrderService {
private PrescriptionOrderRepository prescriptionOrderRepository;
#Autowired
public PrescriptionOrderServiceImpl(PrescriptionOrderRepository prescriptionOrderRepository) {
this.prescriptionOrderRepository = prescriptionOrderRepository;
}
#Override
public List<PrescriptionOrder> orderDatesByPharmacyId(Long pharmacyId, String orderStatus, Boolean status) {
OrderStatusEnum orderStatusEnum = OrderStatusEnum.fromString(orderStatus);
List<PrescriptionOrder> prescriptionOrder = prescriptionOrderRepository
.findByPharmacyIdAndOrderStatus(pharmacyId, orderStatusEnum.getStatus());
return prescriptionOrder;
}
}
The above service is a implementation function to list the orders, where it calls the repository function.
This is my Repository:
package com.axonytes.corporate.repository;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.axonytes.corporate.entity.PrescriptionOrder;
#Repository
public interface PrescriptionOrderRepository extends JpaRepository<PrescriptionOrder, Long>{
//#Query(value = "select * from PrescriptionOrder po WHERE po.pharmacyId = :pharmacyId AND po.orderStatus = :orderStatus AND po.active = :active ORDER BY po.createdAt ASC")
//List<PrescriptionOrder> findByPharmacyIdAndOrderStatus(#Param("pharmacyId") Long pharmacyId, #Param("orderStatus") int orderStatus, #Param("active") Boolean active);
List<PrescriptionOrder> findByPharmacyIdAndOrderStatus(#Param("pharmacyId") Long pharmacyId, #Param("orderStatus") int orderStatus);
}
This is my Entity:
package com.axonytes.corporate.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
#Entity
#DynamicInsert
#DynamicUpdate
#Table(name = "prescription_orders")
public class PrescriptionOrder extends BaseEntity {
private static final long serialVersionUID = -3853355500806579362L;
#Column(name = "prescription_id")
private Long prescriptionId;
#Column(name = "pharmacy_id")
private Long pharmacyId;
#Column(name = "order_status")
private int orderStatus;
public Long getPrescriptionId() {
return prescriptionId;
}
public void setPrescriptionId(Long prescriptionId) {
this.prescriptionId = prescriptionId;
}
public Long getPharmacyId() {
return pharmacyId;
}
public void setPharmacyId(Long pharmacyId) {
this.pharmacyId = pharmacyId;
}
public int getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(int orderStatus) {
this.orderStatus = orderStatus;
}
}
This ismy OrderStatusEnumClass:
package com.axonytes.corporate.util;
public enum OrderStatusEnum {
PENDING(0, "pending"), DESPATCHED(1, "dispatched");
private int status;
private String name;
OrderStatusEnum(int status, String name) {
this.status = status;
this.name = name;
}
public static OrderStatusEnum fromString(String name) {
if(name != null) {
for(OrderStatusEnum orderStatusEnum : OrderStatusEnum.values()) {
if(name.equalsIgnoreCase(orderStatusEnum.toString())) {
return orderStatusEnum;
}
}
}
return null;
}
#Override
public String toString() {
return name;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
I have row values in the mysql:
id prescription_id pharmacy_id order_Status is_active
1 1 6 0 1
I am trying to list a orders by the following api.
http://localhost:8080/pharmacy/order/dates
POST METHOD with JSON VALUE:
{
"pharmacyId":"6",
"orderStatus":"pending"
}
Eventhough i am having 1 rows in the mysql db table, Output i am getting is:
{
"status": "FAILURE",
"errorCode": 0,
"errorMessage": "No pharmacy orders found"
}
Here you are using spring data and name method resolving. So is spring who translate the name of your method with each property in your entity, in that case you don't have to declare any parameter name so change your method to this:
#Repository
public interface PrescriptionOrderRepository extends JpaRepository<PrescriptionOrder, Long>{
List<PrescriptionOrder> findByPharmacyIdAndOrderStatus(Long pharmacyId, int orderStatus);
}
Note: You have an enum OrderStatusEnum but you are saving into the database an integer, I highly recommend you to modify the object to store and change the int for the enum, would be easier to read
I am developing a calories calculator. I have entities Dish (edible item consisting of ingredients or other dishes) and Ingredient (atomic edible, e.g. "water" of "potatoes"). Both extends class AbstractEdible which implements interface Edible.
Dish contains field recipe of type Map<Edible, Double>, where Double represents weight of each "dish element" (ingredient or other dish).
I'm trying to persist all this stuff using JPA and Derby. I expect to have a join table with following fields:
Key of dish entity
DOUBLE value representing weight of "dish element"
Key of "dish element" entity
Here is what I have in reality:
Instead of VARCHAR key to "dish element" entity I have a BLOB and I can't figure out why. Because of that I'm having problems to update existing Dish (getting ERROR 42818: Comparisons between 'BLOB' and 'BLOB' are not supported). I will really appreaciate your help!
Dish
package com.singularityfx.kcalibri2.model.edibles;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.MapKeyJoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Transient;
import javax.persistence.JoinColumn;
#Entity
public class Dish extends AbstractEdible implements EdiblesCollection {
#Transient
private static final long serialVersionUID = -5646610412222252829L;
#ElementCollection
#CollectionTable(name="dish_recipe")
#Column(name="weight")
#MapKeyJoinColumn(name="ingredient_or_dish", referencedColumnName="name")
private Map<Edible, Double> recipe = new HashMap<Edible, Double>();
#Transient
private KCalculator kCalculator = new KCalculator();
public Dish() {}
public Dish(String name, DishCategory category) {
this.name = name;
this.category = category;
}
#Override
public double getKCalNonDessert() {
kCalculator.init(recipe);
return kCalculator.getkCalNonDessertPer100g();
}
#Override
public double getKCalDessert() {
kCalculator.init(recipe);
return kCalculator.getkCalDessertPer100g();
}
#Override
public double getKCal() {
kCalculator.init(recipe);
return kCalculator.getkCalPer100g();
}
#Override
public double getKCalDessertTotal() {
kCalculator.init(recipe);
return kCalculator.getTotalKCalDessert();
}
#Override
public double getKCalNonDessertTotal() {
kCalculator.init(recipe);
return kCalculator.getTotalKCalNonDessert();
}
#Override
public double getKCalTotal() {
kCalculator.init(recipe);
return kCalculator.getTotalKCal();
}
public Double addIngredient(Edible edible, Double weight) {
return recipe.put(edible, weight);
}
public Double removeIngredient(Edible edible) {
return recipe.remove(edible);
}
#Override
public Map<Edible, Double> getContent() {
return recipe;
}
#Override
public void setContent(Map<Edible, Double> content) {
this.recipe = content;
}
#Override
public void clearContent() {
this.recipe.clear();
}
public double getWeight(Edible edible) {
return recipe.get(edible);
}
public Collection<Edible> getEdibles() {
return recipe.keySet();
}
}
Ingredient
package com.singularityfx.kcalibri2.model.edibles;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.NamedQuery;
import javax.persistence.Transient;
#Entity
public class Ingredient extends AbstractEdible {
#Transient
private static final long serialVersionUID = -7669934586986624995L;
private double kCal;
private boolean isDessert;
public Ingredient() {}
public Ingredient(String name, IngredientCategory category,
double kCal, boolean isDessert) {
this.name = name;
this.kCal = kCal;
this.category = category;
this.isDessert = isDessert;
}
#Override
public double getKCalNonDessert() {
return isDessert ? 0 : kCal;
}
#Override
public double getKCalDessert() {
return isDessert ? kCal : 0;
}
}
AbstractEdible
package com.singularityfx.kcalibri2.model.edibles;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.MappedSuperclass;
import javax.persistence.OneToOne;
#Entity
#Inheritance(strategy=InheritanceType.JOINED)
public abstract class AbstractEdible implements Edible, Serializable {
private static final long serialVersionUID = 8684184950268663225L;
#Id
protected String name;
#OneToOne()
#JoinColumn(name="NAME_OF_CATEGORY")
protected EdibleCategory category;
#Override
public String getName() {
return name;
}
#Override
public EdibleCategory getCategory() {
return category;
}
public void setName(String name) {
this.name = name;
}
public void setCategory(EdibleCategory category) {
this.category = category;
}
#Override
public String toString() {
return name + " [" + category + "]";
}
#Override
public int compareTo(Edible c) {
return name.compareTo(c.getName());
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((category == null) ? 0 : category.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AbstractEdible other = (AbstractEdible) obj;
if (category == null) {
if (other.category != null)
return false;
} else if (!category.equals(other.category))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
Edible
package com.singularityfx.kcalibri2.model.edibles;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
public interface Edible extends Comparable<Edible> {
public double getKCalNonDessert();
public double getKCalDessert();
public String getName();
public EdibleCategory getCategory();
}
Your Edible interface extends Comparable. Therefore you should override equals and hashCode, either in the Interface or in the Implementing class. The join requires comparing objects which cannot be compared unless you override equals and hashCode.
My mistake was here:
private Map<Edible, Double> recipe
Edible (interface implemented by my entities) is not an entity itself, therefore persistence provider doesn't recognize map key as entity.
When I refer to abstract class (which is annotaded with #Entity) instead of interface everything works as expected:
private Map<AbstractEdible, Double> recipe
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) {
}
}