I am trying to develop a small web application as training for my upcoming finals and I can't figure out what I'm doing wrong.
These are my *Entities*L Kunde and Konto (many2many-relationship), the auto-created table Kunde_Konto has only the two primary keys of my entities.
#Entity
#NamedQueries({
#NamedQuery(name="findKundeById", query="select k from Kunde k where k.svnr = :svnr"),
})
public class Kunde implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(precision=4, scale=0)
private Long svnr;
#ManyToMany
private List<Konto> konten;
}
#Entity
#NamedQueries({
#NamedQuery(name="findKontoByBesitzer", query="select k from Konto k join k.besitzer b where b.svnr = :svnr")
})
public class Konto implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(precision=4, scale=0)
private Long knr;
#ManyToMany(mappedBy="konten")
private List<Kunde> besitzer;
}
And this is my Managed Bean:
#ManagedBean
#SessionScoped
public class KundenKontoList implements Serializable {
private FacesContext fc = null;
private HttpServletRequest hsr = null;
private HttpSession hs = null;
#EJB
private KontoFacadeLocal kontoFacade;
#EJB
private KundeFacadeLocal kundeFacade;
private Kunde k;
private List<Konto> konten;
/**
* Creates a new instance of KundenKontoList
*/
public KundenKontoList() {
fc = FacesContext.getCurrentInstance();
hsr = (HttpServletRequest) fc.getExternalContext().getRequest();
hs = hsr.getSession();
k = (Kunde) hs.getAttribute("kunde");
konten = kontoFacade.findKontoByBesitzer(k);
}
}
The exception
com.sun.faces.mgbean.ManagedBeanCreationException: Klasse at.pf.controller.KundenKontoList kann nicht instanziiert werden.
which translated means that KundenKontoList can't be instatiated, is thrown at the line:
konten = kontoFacade.findKontoByBesitzer(k);
//method in the facade:
#Override
public List<Konto> findKontoByBesitzer(Kunde k) {
Query q = em.createNamedQuery("findKontoByBesitzer");
q.setParameter("svnr", k.getSvnr());
return q.getResultList();
}
I think that it has something to do with the kontoFacade, but I don't know what the exact problem is.
Fail on init of managedbean, suggests to me that injection of ejbs is failing. Is there a longer error message?
Related
I don't receive the value that I entered in my DB, when I get a response back from Postman. I make and POST Request with Postman and when I verify in my DB it's OK.
When I make a GET Request with Postman, the result of my request is an empty array and I don't know why.
Please need help!
Thank you.
/************* Model *************/
#Entity
#EntityListeners(AuditingEntityListener.class)
#Table
public class RDV implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long idRDV;
#Column(nullable = false)
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm")
#NotNull
private Date dateRDV;
private String nomRDV;
Getters and setters { ... }
/************** Controller ************/
#GetMapping(path="/rdv/getbydate/{dateRDV}")
public List<RDV> getEventsByDate(#PathVariable("dateRDV")
#DateTimeFormat(pattern="yyyy-MM-dd") Date dateRDV)
{
return rdvService.FindByDateRDV(dateRDV);
}
/*************** Service **************/
public interface RDVService {
List<RDV> getRDVs();
RDV saveRDV(RDV rdv);
RDV updateRDV(RDV rdv);
void deleteRDV (Long id);
List<RDV> FindByNomRDV(String nomRDV);
List<RDV> FindByDateRDV(Date dateRDV);
}
/************ Service Implementation **********/
#Override
public List<RDV> FindByDateRDV(Date dateRDV) {
return rdvRepository.findByDateRDV(dateRDV);
}
/*********** Repository ***************/
#Repository
public interface RDVRepository extends JpaRepository<RDV, Long> {
List<RDV> findByNomRDV(String nomRDV);
List<RDV> findByDateRDV(Date dateRDV); }
What I'm expecting is the result of this request :
SELECT daterdv, nomrdv FROM RDV where daterdv LIKE '2018-06-20'
I'm trying to create a simple get request using jersey
but got exception
can someone tell me where I got it wrong?
The excption is - "Caused by: org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.
"
VersionResource.java
#Path("/versions")
public class VersionResource extends BaseResource<VersionDao, VersionTable>
{
public VersionResource(VersionDao objectDao)
{
super(objectDao);
}
#Override
#Path("/getAppVersions")
#GET
#UnitOfWork
public String getAllRecords(#Context HttpServletRequest req, #QueryParam("callback") String callback) throws JsonProcessingException
{
return super.getAllRecords(req, callback);
}
}
VersionTable.java
#Entity(name = "Versions")
#Table(name = "Versions")
#NamedQueries({ #NamedQuery(name = QueryNames.QUERY_VERSION_GET_ALL, query = "select c from Versions c"), })
public class VersionTable extends baseDataBase implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "VersionId")
private short versionId;
#Column(name = "VersionPlatform")
#JsonProperty
#NotEmpty
private String versionPlatform;
#Column(name = "VersionNumber")
#JsonProperty
#NotEmpty
private String versionNumber;
#Column(name = "VersionDescription")
#JsonProperty
#NotEmpty
private String versionDescription;
public short getVersionId()
{
return versionId;
}
public void setVersionId(short versionId)
{
this.versionId = versionId;
}
public String VersionPlatformEnum()
{
return versionPlatform;
}
public void setVersionPlatform(String versionPlatform)
{
this.versionPlatform = versionPlatform;
}
public String getVersionNumber()
{
return versionNumber;
}
public void setVersionNumber(String versionNumber)
{
this.versionNumber = versionNumber;
}
public String getVersionDescription()
{
return versionDescription;
}
public void setVersionDescription(String versionDescription)
{
this.versionDescription = versionDescription;
}
}
VersionDao.java
public class VersionDao extends baseAbstractDao<VersionTable> implements IDatabaseActions<VersionTable>
{
public VersionDao(SessionFactory sessionFactory)
{
super(sessionFactory);
}
#Override
public ObjectDaoResponse getAllTableRecords() throws JsonProcessingException
{
List<VersionTable> list = list(namedQuery(QueryNames.QUERY_VERSION_GET_ALL));
return ObjectDaoResponse.getAnOkResponse(list);
}
}
I think you need a no arg constructor for your VersionResource class, but if you really need an argument the value should be passed by injection (see: https://eclipse-ee4j.github.io/jersey.github.io/documentation/latest/jaxrs-resources.html#d0e2692)
hope somebaody can help me. I have two entities related OneToMany.
First:
#Entity
#Table(name = "repartos")
#XmlRootElement
public class Repartos implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Column(name = "fecha")
#Temporal(TemporalType.DATE)
private Date fecha;
#OneToMany(cascade = {CascadeType.ALL}, mappedBy = "repartoId")
public List<RepartosDetalle> repartosDetalleList;
.....
And then the another one:
#Entity
#Table(name = "repartos_detalle")
#XmlRootElement
public class RepartosDetalle implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#JoinColumn(name = "reparto_id", referencedColumnName = "id")
#ManyToOne(optional = false)
private Repartos repartoId;
#Column(name = "descargado")
#Convert(converter = BooleanOneZeroConverter.class)
private boolean descargado;
public RepartosDetalle() {
}
public RepartosDetalle(Repartos repartoId) {
this.repartoId = repartoId;
}
public Repartos getRepartoId() {
return repartoId;
}
public void setRepartoId(Repartos repartoId) {
this.repartoId = repartoId;
}
public boolean isDescargado() {
return descargado;
}
public void setDescargado(boolean descargado) {
this.descargado = descargado;
}
}
What I try to get is all the Repartos given a date and where they have al least one RepartosDetalle with the property descargado=TRUE.
I've been trying with the following query but I do't get any result.
#Override
public List<Repartos> buscarPorFechaDescargados(Date searchDate) {
Query q = em.createQuery("SELECT e FROM Repartos e "
+ "WHERE e.fecha = :searchDate"
+ " AND e.repartosDetalleList.descargado=TRUE");
q.setParameter("searchDate", searchDate);
return q.getResultList();
}
Is there a proper way to make this query using one of the collection's property value?
Thanks a lot and nice weekend.
Try to use JOIN operator on these 2 entities - Repartos and RepartosDetalle :
SELECT e FROM Repartos e JOIN RepartosDetalle d
WHERE e.fecha = :searchDate
AND d.descargado = TRUE
I can't get the right mapping for the field tree in this class:
#Entity
#Table(name = "SushiMapTree")
public class SushiMapTree<K, V> extends Persistable implements Map<K,V> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="SushiMapID")
protected int ID;
#OneToOne(cascade = CascadeType.ALL)
#JoinTable(name="SushiMapTree_SushiTree")
private SushiTree<SushiMapElement<K, V>> tree = new SushiTree<SushiMapElement<K,V>>();
This are the other classes and their mappings:
#Entity
#Table(name = "SushiTree")
public class SushiTree<T> extends Persistable implements Collection<T> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="SushiTreeID")
protected int ID;
#Column(name="Test")
private String test = "Test";
#OneToMany(cascade = CascadeType.PERSIST)
#JoinTable(name="SushiTree_SushiTreeElements")
private List<SushiTreeElement<T>> treeElements = new ArrayList<SushiTreeElement<T>>();
#OneToMany(cascade = CascadeType.PERSIST)
#JoinTable(name="SushiTree_SushiTreeRootElements")
private List<SushiTreeElement<T>> treeRootElements = new ArrayList<SushiTreeElement<T>>();
}
#Entity
#Table(name = "SushiMapElement")
public class SushiMapElement<K, V> extends Persistable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int ID;
#ManyToOne(cascade = CascadeType.PERSIST)
private SushiMapElement<K, V> parent;
#OneToMany(cascade = CascadeType.PERSIST)
private List<SushiMapElement<K, V>> children = new ArrayList<SushiMapElement<K, V>>();
#Column(name = "MapKey")
K key;
#Column(name = "MapValue")
V value;
The other classes work well, but I can't get the right mapping. I tried different mappings for some hours with Column, JoinColumn, JoinTable and so on. Eclipse Link does not create the database and says to use a ValueHolderInterface:
The attribute [tree] is not declared as type ValueHolderInterface, but its mapping uses indirection.
Thanks for your help!
I solved the problem with the following annotation:
#ManyToOne(cascade=CascadeType.PERSIST)
#JoinColumn(name="TreeID")
But I don't know, why it work this way.
This has bugged me for years but I cannot find anything about it in jpa references nor this site. When an entity has a computed member (Inverse via mappedby, #Formula, ...), there doesn't seem to be any way to get a transactionally consistent update of that computed member. The pattern seems to be that the setter of the one side needs to know about the consumers and update them in situ. I must be missing something. Hopefully the below is illustrative enough.
I wouldn't mind if the requirement was that I had to call em.getReference or .find again on the obj w/ the computed members just in case the ones from the original fetch are out of sync, but that just returns the exact same instance w/ no updates of the fields.
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;
#Entity
public class InverseProblemDto {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#OneToMany(mappedBy="problem")
public Set<OwnerDto> owners;
public int otherField = 0;
}
#Entity
public class OwnerDto {
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private int id;
#ManyToOne
public InverseProblemDto problem;
public int yetAnotherField = 0;
}
#Transactional
public void wontWork(int dbId) {
#PersistenceContext
EntityManager em;
InverseProblemDto probDto = em.find(InverseProblemDto.class, dbId);
probDto.otherField++;
for (OwnerDto other : probDto.owners) {
// do something
}
OwnerDto newOwner = new OwnerDto();
newOwner.problem = probDto;
em.persist(newOwner);
// do more
// How to ensure this finds newOwner w/o breaking transactional integrity by forcing a flush and refresh???
for (OwnerDto other : probDto.owners) {
if (other.id == newOwner.id) System.out.println("Yeah! found it");
}
}
Flush and refresh do not commit the transaction but only issue the pending sql to the database.
You could always change the value yourself like this :
#Entity
public class InverseProblemDto {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#OneToMany(mappedBy="problem")
public Set<OwnerDto> owners;
public int otherField = 0;
public void addOwner(OwnerDto owner) {
...
}
}
#Entity
public class OwnerDto {
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private int id;
#ManyToOne
public InverseProblemDto problem;
public int yetAnotherField = 0;
public void setProblem(InverseProblemDto problem) {
if(problem != null) {
problem.addOwners(this);
}
this.problem = problem;
}
}