This JPQL used to work but then it broke for no reason. I now get this strange exception:
java.lang.IllegalArgumentException: Parameter "Parameter<LandKod>('landKod')" declared in "SELECT r FROM Region r WHERE r.landKod = :landKod" is set to value of "US" of type "java.lang.String", but this parameter is bound to a field of type "se.prv.pandora.arendeprocess.entity.LandKod".
which seems to indicate that there is some kind of name conflict of what is named landKod in my code. Here is the source:
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
#Entity(name = "Region")
#Table(name="TP197_REGION")
#NamedQueries({
#NamedQuery(name = "getAllValidRegions", query = "SELECT r FROM Region r WHERE r.histKod = 'A'"),
#NamedQuery(name = "getRegionsByLandkod", query = "SELECT r FROM Region r WHERE r.landKod = :landKod")
})
public class Region implements Serializable {
#Id
private int regionId;
#ManyToOne
#JoinColumn(name="landKod", referencedColumnName="landKod")
private LandKod landKod ;
private String histKod ;
private String regionForkort;
private String regionRubrik;
private String regionBeskr;
public Region() {
super();
}
public int getRegionId() {
return regionId;
}
public void setRegionId(int regionId) {
this.regionId = regionId;
}
public String getRegionForkort() {
return regionForkort;
}
public void setRegionForkort(String regionForkort) {
this.regionForkort = regionForkort;
}
public String getRegionRubrik() {
return regionRubrik;
}
public void setRegionRubrik(String regionRubrik) {
this.regionRubrik = regionRubrik;
}
public String getRegionBeskr() {
return regionBeskr;
}
public void setRegionBeskr(String regionBeskr) {
this.regionBeskr = regionBeskr;
}
public String getHistKod() {
return histKod;
}
public void setHistKod(String histKod) {
this.histKod = histKod;
}
public String getRegionFormatted() {
if(regionForkort!=null && regionForkort.length()>0) {
return regionForkort + " " + regionRubrik;
} else {
return regionRubrik;
}
}
public LandKod getLandKod() {
return landKod;
}
public void setLandKod(LandKod landKod) {
this.landKod = landKod;
}
}
Here's the method implementation where it allows a string as a parameter:
#Override
public List<Region> getRegionsByLandkod(String landKod) {
List<Region> regionsList = null;
try {
Query query = em.createNamedQuery("getRegionsByLandkod");
query.setParameter("landKod", landKod);
regionsList = (List<Region>) query.getResultList();
} catch(Exception e){
logger.info("Kunde inte hitta nĂ¥gon region med landkod: "+landKod, e);
}
return regionsList;
}
Could you help me fix this error?
The problem is this line:
public List<Region> getRegionsByLandkod(String landKod) {
It should either be this:
public List<Region> getRegionsByLandkod(LandKod landKod) {
or you should be converting the String to a LandKod and using that as the query parameter.
(Or you could change the Region class to make the landKod attribute's type String.)
It seems you're calling getRegionsByLandkod with a String instead of a LandKod object.
Verify where you use this query if the parameter is correct.
Related
I have modelled a car park with building and floor models. There is a one to many relationship between building and floor. I have built a rest controllers to retrieve the data. I am attempting to retrive the data via a simple get request to api/v1/parkingbuildings/1/. The issue is that when retrieving a building i do not see a list of floors as per my relation mapping. Any insight into any mistakes i may be making would be appreciated. Below is the json that gets returned;
{"building_id":1,"building_name":"Labadiestad","postcode":"SA78BQ","max_floors":14,"owner_name":"Schaefer, Gutmann and Braun"}
I am expecting to see a collection of floors in the payload and i cannot fathom why, ive written other similar simpler solutions that do the same without issue, ive compared my prior solutions and see little difference that matters in my approach.
Here is my building model
package com.admiral.reslink.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity(name = "parking_buildings")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class ParkingBuilding {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long building_id;
private String building_name;
private String postcode;
private int max_floors;
private String owner_name;
// ToDo sort the relationships
#OneToMany(mappedBy = "parkingBuilding")
#JsonIgnore
private List<ParkingFloor> parkingFloors;
public ParkingBuilding() {
}
public long getBuilding_id() {
return building_id;
}
public void setBuilding_id(long building_id) {
this.building_id = building_id;
}
public String getBuilding_name() {
return building_name;
}
public void setBuilding_name(String building_name) {
this.building_name = building_name;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public int getMax_floors() {
return max_floors;
}
public void setMax_floors(int max_floors) {
this.max_floors = max_floors;
}
public String getOwner_name() {
return owner_name;
}
public void setOwner_name(String owner_name) {
this.owner_name = owner_name;
}
public List<ParkingFloor> getParkingFloors() {
return parkingFloors;
}
public void setParkingFloors(List<ParkingFloor> parkingFloors) {
this.parkingFloors = parkingFloors;
}
}
And here is my floor model
package com.admiral.reslink.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "parking_floors")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class ParkingFloor {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long floor_id;
private int floor_number;
private int max_height_inches;
private boolean is_covered;
private boolean is_disabled_access;
// ToDo sort the relationships
#ManyToOne
#JoinColumn(name="building_id", nullable=false)
private ParkingBuilding parkingBuilding;
#OneToMany(mappedBy = "parkingFloor")
#JsonIgnore
private List<ParkingSpace> parkingSpace;
public ParkingFloor() {
}
public long getFloor_id() {
return floor_id;
}
public void setFloor_id(long floor_id) {
this.floor_id = floor_id;
}
public int getFloor_number() {
return floor_number;
}
public void setFloor_number(int floor_number) {
this.floor_number = floor_number;
}
public int getMax_height_inches() {
return max_height_inches;
}
public void setMax_height_inches(int max_height_inches) {
this.max_height_inches = max_height_inches;
}
public boolean isIs_covered() {
return is_covered;
}
public void setIs_covered(boolean is_covered) {
this.is_covered = is_covered;
}
public boolean isIs_disabled_access() {
return is_disabled_access;
}
public void setIs_disabled_access(boolean is_disabled_access) {
this.is_disabled_access = is_disabled_access;
}
public ParkingBuilding getParkingBuilding() {
return parkingBuilding;
}
public void setParkingBuilding(ParkingBuilding parkingBuilding) {
this.parkingBuilding = parkingBuilding;
}
public List<ParkingSpace> getParkingSpace() {
return parkingSpace;
}
public void setParkingSpace(List<ParkingSpace> parkingSpace) {
this.parkingSpace = parkingSpace;
}
}
Here is my building controller
package com.admiral.reslink.controllers;
import com.admiral.reslink.models.ParkingBuilding;
import com.admiral.reslink.models.ParkingFloor;
import com.admiral.reslink.repositories.ParkingBuildingRepository;
import com.admiral.reslink.repositories.ParkingFloorRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
#RequestMapping("/api/v1/parkingbuildings")
public class ParkingBuildingController {
#Autowired
private ParkingBuildingRepository parkingBuildingRepository;
#GetMapping
public List<ParkingBuilding> list() {return parkingBuildingRepository.findAll();}
#GetMapping
#RequestMapping("{id}")
public ParkingBuilding get(#PathVariable Long id) {return parkingBuildingRepository.getById(id);}
#PostMapping
public ParkingBuilding create(#RequestBody final ParkingBuilding parkingBuilding) {
return parkingBuildingRepository.saveAndFlush(parkingBuilding);
}
#RequestMapping(value="{id}", method = RequestMethod.DELETE)
public void delete(#PathVariable Long id) {
parkingBuildingRepository.deleteById(id);
}
#RequestMapping(value="{id}", method = RequestMethod.PUT)
public ParkingBuilding update(#PathVariable Long id, #RequestBody ParkingBuilding parkingBuilding) {
ParkingBuilding existingParkingBuilding = parkingBuildingRepository.getById(id);
BeanUtils.copyProperties(parkingBuilding, existingParkingBuilding, "building_id");
return parkingBuildingRepository.saveAndFlush(existingParkingBuilding);
}
}
Not sure how you are retrieving the floors. OneToMany is by default lazy and would not load unless asked.
In your repository, try:
#EntityGraph(attributePaths = "parkingFloors")
ParkingBuilding findById(long id);
The below query is working fine in mysql.
SELECT * FROM utilization u INNER JOIN sbg s on s.sbg_code=u.sbg_code where u.sbg_code=104
I have written below JPQL query.
#Query("SELECT i FROM Utilization i,i.sbg s where s.sbgCode = :sbgCode")
public ArrayList<Utilization> findUtilization(#Param("sbgCode") int sbgCode);
I am getting below error, please tell how to resolve this error
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: i.sbg is not mapped [SELECT i FROM be.g00glen00b.model.Utilization i,i.sbg s where s.sbgCode = :sbgCode]
Can you please tell me how to write the above sql query to JPQL query?
Please suggest some link to learn JPQL joins because I am new to this.
Below class represents the mapping between two tables
sbg class
#Entity
public class sbg {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int sbgCode;
private String sbgdesc;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="iccode")
#JsonIgnore
private Ic ic;
#OneToMany(mappedBy="sbg1", fetch=FetchType.EAGER)
private List<Utilization> utilization;
public int getSbgCode() {
return sbgCode;
}
public void setSbgCode(int sbgCode) {
this.sbgCode = sbgCode;
}
public String getSbgdesc() {
return sbgdesc;
}
public void setSbgdesc(String sbgdesc) {
this.sbgdesc = sbgdesc;
}
public Ic getIc() {
return ic;
}
public void setIc(Ic ic) {
this.ic = ic;
}
}
utilization class
package be.g00glen00b.model;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
public class Utilization {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int asset_type_key;
private String asset_type;
private String Engine_status;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "sbgCode")
private sbg sbg1;
public sbg getSbg1() {
return sbg1;
}
public void setSbg1(sbg sbg1) {
this.sbg1 = sbg1;
}
public int getAsset_type_key() {
return asset_type_key;
}
public void setAsset_type_key(int asset_type_key) {
this.asset_type_key = asset_type_key;
}
public String getAsset_type() {
return asset_type;
}
public void setAsset_type(String asset_type) {
this.asset_type = asset_type;
}
public String getEngine_status() {
return Engine_status;
}
public void setEngine_status(String engine_status) {
Engine_status = engine_status;
}
}
jpa repository
public interface UtilizationRepository extends JpaRepository<Utilization, Integer> {
#Query("SELECT i FROM Utilization i,i.sbg s where s.sbgCode = :sbgCode")
public ArrayList<Utilization> findUtilization(#Param("sbgCode") int sbgCode);
}
You are missing a JOIN in your query.
Your query should look like
SELECT i FROM Utilization i JOIN i.sbg s where s.sbgCode = :sbgCode
When you do queries like this you need to keep in mind that you might get duplicate results back. If you want to get unique results you should use a Set or have a look at this for a way to achieve it with hints and hibernate.
i dont know who send image server to web service, using json, my method for send:
#POST
#Path("imagenGuardar")
#Consumes({("application/json")})
#Produces("text/plain")
public int guarda(Imagenes entity) {
em.persist(entity);
return entity.getIdImagenes();
}
This my entity from database:
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author Valar_Morgulis
*/
#Entity
#Table(name = "imagenes")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Imagenes.findAll", query = "SELECT i FROM Imagenes i"),
#NamedQuery(name = "Imagenes.findByIdImagenes", query = "SELECT i FROM Imagenes i WHERE i.idImagenes = :idImagenes"),
#NamedQuery(name = "Imagenes.findByDescripcion", query = "SELECT i FROM Imagenes i WHERE i.descripcion = :descripcion")})
public class Imagenes implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "ID_IMAGENES")
private Integer idImagenes;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "DESCRIPCION")
private String descripcion;
#Lob
#Column(name = "IMAGEN")
private byte[] imagen;
#JoinColumn(name = "ID_ACTIVO", referencedColumnName = "ID_ACTIVO")
#ManyToOne(optional = false)
private Activo idActivo;
public Imagenes() {
}
public Imagenes(Integer idImagenes) {
this.idImagenes = idImagenes;
}
public Imagenes(Integer idImagenes, String descripcion) {
this.idImagenes = idImagenes;
this.descripcion = descripcion;
}
public Integer getIdImagenes() {
return idImagenes;
}
public void setIdImagenes(Integer idImagenes) {
this.idImagenes = idImagenes;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public byte[] getImagen() {
return imagen;
}
public void setImagen(byte[] imagen) {
this.imagen = imagen;
}
int activo;
public int getIdActivo() {
return idActivo.getIdActivo();
}
public void setIdActivo(int idActivo) {
this.activo = idActivo;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idImagenes != null ? idImagenes.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Imagenes)) {
return false;
}
Imagenes other = (Imagenes) object;
if ((this.idImagenes == null && other.idImagenes != null) || (this.idImagenes != null && !this.idImagenes.equals(other.idImagenes))) {
return false;
}
return true;
}
#Override
public String toString() {
return "activo.entities.Imagenes[ idImagenes=" + idImagenes + " ]";
}
}
And send data as follows:
[{"descripcion":"Imagen trasera","idActivo":84,"idImagenes":7,"imagen":"R0lGODlhEAAQAPfAAAgAAPgAAP8JCQhUAAZBAABgmAAGCg6ZAI/W//X79Pf89wAQGju3/+/3+z9wjQCc+GbG/+/x8uPz4Q6YAAAGAAAaKgCR5gpoAACH1u/5//YAABehCSanGEWzOePw4e/z9SgAAABWiP+Hh/9eXpXLjwBMebDAr+/2+gMkAKgAAGkAAP8uLvH5/5CZj+zx7Pz+/P8eHnkAAIgAAOT1/5gAABGn//+cnC9WbO/y9Njv1vz+/zmvLPT7/wAtSEkAAMnr/4+eprgAAAB1uu/1+LPdr5Cej4+aoAA4Wuf2/wCS5//Pz8joxP/T04/H6I/H583rygZAAAAkOkJhP+cAAK3eqP9zc/L68d/y3Yp/fwCI10u2QP8zM+P04f9ISP+ysq+zr0eUP/L68gleADRdLwIaAAARHAU2AGjCXkBKPxkAAIGXfw2PAAoAAAU3AFkAAI+epy9EUQAHAI/M74+ntgEQAI++2QAbK+Dy3rrl/wyl/zkAAPR/f+Tw4y+NxIXOfk++/wppAHDFZ//c3ABCai+f4ACS6DeELwB+x//Hx4S3f/j8+G7J/0qsPwBqqENiP//x8QyGAEV4P93x2ssPD3vKcwdLAAyFAACI2EeVP7LQrwt7AOf15tgAANoPDwldAIKgf4Suf6jcome0X8gAAGWbX3HFaN7x3O/y7yAkH9HszghTAC9+rMDlvOvx6glfAJTGjy9FUcLfvwt8AA2OAJTTjS+e3wpyAEV/P+34/1O5SNzw2Y/Shw2QAMXnwf8AAP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAMAALAAAAAAQABAAAAjGAIEJFDjhgMEDEwYqBLZmDZFfEH8RabjQEgkJgThs2MAhkAQSlgZqepVjB4eTKHfkeKVJ4IVNWjrIhCizg5ZNF4BdyEQrl89cEH/mopXpgphfpc4oPQNx6ZlSv8QM+EWJUsSrVK0OqPRr1y6sEb3+qkTgV6hQByEePPuLQBsTqYjIfShxbioTbYBJUfCk7xOIfp8okCIQRREFd65cMaj4joIiKAaSafEiQRgrVsIkeNGCzEI6aL5c/YKGzsKBcSigokAhzsKAADs="}]
The image is format BASE64, but throws me the following error:
javax.servlet.ServletException: Exception [EclipseLink-6065] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.QueryException
Exception Description: Cannot add the object [activo.entities.Imagenes[ idImagenes=0 ]], of class [class activo.entities.Imagenes], to container [class activo.entities.Imagenes].
Internal Exception: java.lang.ClassCastException: activo.entities.Imagenes cannot be cast to java.util.Collection
as it should send the form? Thanks
I just needed to remove the brackets , remove the GlassFish default has netbeans , delete all records and install a new one.
So I stick to insert the image into base64 to database
{"descripcion":"Imagen trasera","idActivo":{"idActivo":"84"},"idImagenes":0,"imagen":"R0lGODlhEAAQAPfAAAgAAPgAAP8JCQhUAAZBAABgmAAGCg6ZAI/W//X79Pf89wAQGju3/+/3+z9wjQCc+GbG/+/x8uPz4Q6YAAAGAAAaKgCR5gpoAACH1u/5//YAABehCSanGEWzOePw4e/z9SgAAABWiP+Hh/9eXpXLjwBMebDAr+/2+gMkAKgAAGkAAP8uLvH5/5CZj+zx7Pz+/P8eHnkAAIgAAOT1/5gAABGn//+cnC9WbO/y9Njv1vz+/zmvLPT7/wAtSEkAAMnr/4+eprgAAAB1uu/1+LPdr5Cej4+aoAA4Wuf2/wCS5//Pz8joxP/T04/H6I/H583rygZAAAAkOkJhP+cAAK3eqP9zc/L68d/y3Yp/fwCI10u2QP8zM+P04f9ISP+ysq+zr0eUP/L68gleADRdLwIaAAARHAU2AGjCXkBKPxkAAIGXfw2PAAoAAAU3AFkAAI+epy9EUQAHAI/M74+ntgEQAI++2QAbK+Dy3rrl/wyl/zkAAPR/f+Tw4y+NxIXOfk++/wppAHDFZ//c3ABCai+f4ACS6DeELwB+x//Hx4S3f/j8+G7J/0qsPwBqqENiP//x8QyGAEV4P93x2ssPD3vKcwdLAAyFAACI2EeVP7LQrwt7AOf15tgAANoPDwldAIKgf4Suf6jcome0X8gAAGWbX3HFaN7x3O/y7yAkH9HszghTAC9+rMDlvOvx6glfAJTGjy9FUcLfvwt8AA2OAJTTjS+e3wpyAEV/P+34/1O5SNzw2Y/Shw2QAMXnwf8AAP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAMAALAAAAAAQABAAAAjGAIEJFDjhgMEDEwYqBLZmDZFfEH8RabjQEgkJgThs2MAhkAQSlgZqepVjB4eTKHfkeKVJ4IVNWjrIhCizg5ZNF4BdyEQrl89cEH/mopXpgphfpc4oPQNx6ZlSv8QM+EWJUsSrVK0OqPRr1y6sEb3+qkTgV6hQByEePPuLQBsTqYjIfShxbioTbYBJUfCk7xOIfp8okCIQRREFd65cMaj4joIiKAaSafEiQRgrVsIkeNGCzEI6aL5c/YKGzsKBcSigokAhzsKAADs="}
I'm trying to develop a blacklist for my users including several variables. So when a user sign up in my application, I check if some parameters are blacklisted or not.
The problem is that when I perform a select and the database find something that fits with my search, it automatically perform an update an clean that row.
This is the MySQL log:
86 Query select * from blacklist where mobile_token = 'b'
86 Query SHOW WARNINGS
86 Query select ##session.tx_read_only
86 Query update mydatabase.blacklist set email=null, iban=null, mobile_token=null, nif=null where blacklist_id=1
86 Query SHOW WARNINGS
86 Query commit
86 Query SET autocommit=1
86 Query SET autocommit=1
86 Query set session transaction read write
This is my table:
My model:
package models.classes_hibernate;
import javax.persistence.*;
import static javax.persistence.GenerationType.IDENTITY;
#Entity
#Table(name="blacklist"
,catalog="mydatabase"
)
public class Blacklist implements java.io.Serializable {
private Integer blacklistId;
private String mobileToken;
private String iban;
private String nif;
private String email;
public Blacklist() {
}
#Id #GeneratedValue(strategy=IDENTITY)
#Column(name="blacklist_id", unique=true, nullable=false)
public Integer getBlacklistId() {
return this.blacklistId;
}
public void setBlacklistId(Integer blacklistId) {
this.blacklistId = blacklistId;
}
#Column(name="mobile_token", nullable = false)
public String getMobileToken() {
return this.mobileToken;
}
public void setMobileToken(String name) {
this.mobileToken = mobileToken;
}
#Column(name="iban", nullable = false)
public String getIban() {
return this.iban;
}
public void setIban(String name) {
this.iban = iban;
}
#Column(name="nif", nullable = false)
public String getNif() {
return this.nif;
}
public void setNif(String name) {
this.nif = nif;
}
#Column(name="email", nullable = false)
public String getEmail() {
return this.email;
}
public void setEmail(String name) {
this.email = email;
}
}
And my DAO:
package models.dao;
import com.google.common.collect.Lists;
import models.classes_hibernate.Blacklist;
import models.pages.Page;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.hibernate.type.StringType;
import play.Logger;
import play.db.jpa.JPA;
import play.db.jpa.Transactional;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import java.util.List;
public class BlacklistDAOImpl implements MyAppCRUDDAOInterface<Blacklist> {
#Override
public void create(Blacklist entity) {
JPA.em().persist(entity);
}
#Override
public Blacklist read(Integer id) {
return JPA.em().find(Blacklist.class, id);
}
public Page<Blacklist> readAll(String orientation,int pageSize, int beginElementId)
{
Query query = null;
List<Blacklist> blacklists = null;
boolean areThereMore = false;
Page<Blacklist> allBlacklists = null;
int size = 0;
if(orientation.equals("all")) {
query = JPA.em().createNativeQuery("select * from blacklist",Blacklist.class);
}
if(orientation.equals("lt")) {
query = JPA.em().createNativeQuery("select * from blacklist where blacklist_id < ? ORDER BY blacklist_id DESC",Blacklist.class);
query.setParameter(1, beginElementId);
size =query.getResultList().size();
query.setMaxResults(pageSize);
}
if(orientation.equals("gt")) {
query = JPA.em().createNativeQuery("select * from blacklist blacklist_id > ? ORDER BY blacklist_id ASC",Blacklist.class);
query.setParameter(1, beginElementId);
size =query.getResultList().size();
query.setMaxResults(pageSize);
}
if (size>pageSize)
areThereMore = true;
try {
blacklists = query.getResultList();
if (orientation.equals("gt")) {
List<Blacklist> reverseList = Lists.reverse(blacklists);
blacklists = reverseList;
}
allBlacklists = new Page<Blacklist>(blacklists, areThereMore, "Blacklist");
return allBlacklists;
}
catch(NoResultException nre){
allBlacklists=null;
return allBlacklists;
}
}
#Override
public void update(Blacklist entity) {
JPA.em().merge(entity);
}
#Override
public void delete(Blacklist entity) {
JPA.em().remove(entity);
}
#Override
public boolean isManaged(Blacklist entity) {
return JPA.em().contains(entity);
}
#Override
public void close() {
JPA.em().close();
}
public Boolean isMobileTokenBlacklisted(String mobileToken) {
Query query = JPA.em().createNativeQuery("select * from blacklist where mobile_token = ?",Blacklist.class);
query.setParameter(1, mobileToken);
Blacklist blacklist;
try {
Logger.debug("Voy a comprobar");
blacklist = (Blacklist)query.getSingleResult();
} catch (NoResultException nre){
blacklist=null;
}
return blacklist != null;
}
isMobileTokenBlacklisted call:
#POST
#Path("/api/user")
#ApiOperation(position = 3, nickname ="user", value = "Sign up new user",notes = "Minimum JSON required: ",
response = AppUserJSON.class, httpMethod = "POST")
#BodyParser.Of(BodyParser.Json.class)
#Transactional
public static Result signup() {
AppUserDAOImpl appUserDAO = new AppUserDAOImpl();
AppUserJSON user = null;
AppUser appUser = null;
BlacklistDAOImpl blacklistDAO = new BlacklistDAOImpl();
try {
user = parse();
String encrypt_nif = user.nif;
String encrypt_authorization = user.parental_authorization;
String encrypt_password = user.password;
try {
encrypt_password= EncryptUtils.encrypt(config1.getString("key"),user.password);
if(user.nif!= null)
encrypt_nif = EncryptUtils.encrypt(config1.getString("key"),user.nif);
if(user.parental_authorization!= null)
encrypt_authorization = EncryptUtils.encrypt(config1.getString("key"),user.parental_authorization);
} catch (Exception e) {
e.printStackTrace();
}
appUser = new AppUser(new Date(), new Date(),user.email.toLowerCase(), encrypt_password, user.mobile_token,
user.mobile_device, 0, 0, 0, 0, encrypt_nif,
false,"NOT_LOCKED", encrypt_authorization, 0, false);
if (user.email == null) {
return status (200, "email missing");
} else if (blacklistDAO.isEmailBlacklisted(user.email)){
return status(401, "Email is blacklisted");
}
if (user.password == null)
return status(201, "password missing");
if (user.mobile_token == null) {
return status (206, "mobileToken missing");
} else if (blacklistDAO.isMobileTokenBlacklisted(user.mobile_token)){
Logger.debug("MobileToken blacklisted");
return status(401, "Mobile token is blacklisted");
}
if (user.mobile_device== null)
return status(207, "mobileDevice missing");
else{
appUserDAO.create(appUser);
user.app_user_id= appUser.getAppUserId();
return ok(Json.toJson(user));
}
} catch (IncompleteJSONException e) {
return badRequest("IncompleteJSONException");
} catch (DuplicateJSONException e) {
return badRequest("DuplicateJSONException");
}
}
Thanks!
I don't know where it comes from but we can find a way to correct some thing to improve your code and exclude definitely some queries.
Be sure to use bracket around your if. It's not compulsory but is a way to make the code clearer
In the signup method, the else is not logical. It only depends on the last if (mobiledevice test). You probably want to create your user if all test are wrong.
Here you just want to test if you have any blacklisted element corresponding to your research. You can use COUNT function or even EXISTS which can be more efficient maybe.
You can use Debug mode to see where your update is done too.
I have created an object which maps two tables in my database, the Dictionary table and the Token table. The object (class) that represents the join between these two tables is called DictionaryToken.
Here is the class:
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.apache.log4j.Logger;
#Entity
#Table(name="dictionary", catalog="emscribedxcode")
public class DictionaryToken {
private static Logger LOG = Logger.getLogger(DictionaryToken.class);
private Long _seq;
private String _code;
private String _acute;
private String _gender;
private String _codeType;
private String _papplydate;
private String _capplydate;
private Long _tokenLength;
private List <TokenDictionary> _token;
private int _type;
private String _system;
private String _physicalsystem;
/*
* type of 0 is a straight line insert type of 1 is a language dictionary
* entyr type of 2 is a multiple token entry
*/
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "seq")
public Long getSeq() {
return _seq;
}
public void setSeq(Long seq_) {
_seq = seq_;
}
#Column(name = "code")
public String getCode() {
return _code;
}
public void setCode(String code_) {
_code = code_;
}
#Column(name = "acute")
public String getAcute() {
return _acute;
}
public void setAcute(String acute_) {
_acute = acute_;
}
#Column(name = "gender")
public String getGender() {
return _gender;
}
public void setGender(String gender_) {
_gender = gender_;
}
#Column(name = "codetype")
public String getCodeType() {
return _codeType;
}
public void setCodeType(String codeType_) {
_codeType = codeType_;
}
#Column(name = "papplydate")
public String getPapplydate() {
return _papplydate;
}
public void setPapplydate(String papplydate_) {
_papplydate = papplydate_;
}
#Column(name = "capplydate")
public String getCapplydate() {
return _capplydate;
}
public void setCapplydate(String capplydate_) {
_capplydate = capplydate_;
}
#Column(name = "token_length")
public Long getTokenLength() {
return _tokenLength;
}
public void setTokenLength(Long tokenLength_) {
_tokenLength = tokenLength_;
}
#OneToMany (mappedBy = "dictionarytoken", targetEntity = TokenDictionary.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public List<TokenDictionary> get_token() {
return _token;
}
public void set_token(List<TokenDictionary> _token) {
this._token = _token;
}
public void addToToken(TokenDictionary token){
this._token.add(token);
}
#Column(name = "type")
public int getType() {
return _type;
}
public void setType(int _type) {
this._type = _type;
}
#Column(name = "physicalsystem")
public String get_physicalsystem() {
return _physicalsystem;
}
public void set_physicalsystem(String _physicalsystem) {
this._physicalsystem = _physicalsystem;
}
#Column(name = "codingsystem")
public String get_system() {
return _system;
}
public void set_system(String _system) {
this._system = _system;
}
}
Here is my problem. I can perform queries using a service with this object with no problems UNLESS I add a criteria. Here is the method which retrieves the entries
public List<DictionaryToken> getDictionaryTokenEntries(String system) {
Session session = null;
List<DictionaryToken> dictonaries = new ArrayList<DictionaryToken>();
try {
session = HibernateUtils.beginTransaction("emscribedxcode");
session.createCriteria(Dictionary.class).addOrder(Order.desc("codeType"))
Criteria criteria = session.createCriteria(DictionaryToken.class);
/*******THIS IS THE PROBLEM STATEMENT*************************/
if (system != null) {
criteria.add(Restrictions.eq("codingsystem", system));
}
/****************************************************************/
// dictonaries = criteria.list();
Order order = Order.asc("seq");
criteria.addOrder(order);
dictonaries = criteria.list();
System.out.println("Dictionaryentries = " + dictonaries.size());
// System.out.println("Dictionaries entries EVICT start...");
// for(Dictionary dic : dictonaries){
// session.evict(dic);
// }
// System.out.println("Dictionaries entries EVICT end");
} catch (HibernateException e_) {
e_.printStackTrace();
NTEVENT_LOG.error("Error while getting List of Dictionary entries");
} finally {
if (session != null && session.isOpen()) {
try {
HibernateUtils.closeSessions();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return dictonaries;
}
When I add the criteria, I get the following error:
org.hibernate.QueryException: could not resolve property: coding system of : com.artificialmed.domain.dictionary.model.DictionaryToken
I know that it has something to do with the nature of the object which is really a join between my dictionary class and the underlying table and my token class and table.
The field codingsystem is a field in my dictionary class. I think I am suppose to use aliases but I don't know how to do this under the current circumstances. Any help would be greatly appreciated.
Elliott
This was a newbie problem. Hibernate requires the getters and setters of the models that reflect the tables to be of a specific format. The getter MUST BE get+ where name is the fieldname in the underlying table. The setter MUST BE set+ where name is the fieldname of the underlying table. And yes the first letter of Name must capitalized.