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.
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);
I am new to Spring Data JPA and Hibernate. By looking at different examples I built a working model for CRUD operations on one entity, I am having trouble in joining two tables to extract AF_NAME using AF_ID from another table which is Foreign key. A null column is created with the names of and while accessing, null is returned.please check if I am following preocedure for joins and point me to any tutorial know.
I followed this solution and still there is no progress.
#Entity
#Configuration
#EnableAutoConfiguration
#Table(name = "AFF_CONFIG")
public class AFF_CONFIG implements Serializable {
#Id
#Column(name = "AFF_CONFIG_ID")
private String AFF_CONFIG_ID;
#Column(name = "AFF_ID")
private String AFF_ID;
#Column(name = "CH_ID")
private String CH_ID;
#Column(name = "M_ID")
private Long M_ID;
#Column(name = "KEY")
private String KEY;
#Column(name = "VALUE")
private String VALUE;
#Column(name = "SYSTEM")
private String SYSTEM;
private AFF aff;
#LazyCollection(LazyCollectionOption.TRUE)
#ManyToOne
#JoinColumn(name = "AFF_ID")
public AFF getAff() {
return aff;
}
public void setAffiliate(AFF aff) {
this.aff = aff;
}
public String getAFF_CONFIG_ID() {
return AFF_CONFIG_ID;
}
public void setAFF_CONFIG_ID(String aFF_CONFIG_ID) {
AFF_CONFIG_ID = aFF_CONFIG_ID;
}
public String getAFF_ID() {
return AFF_ID;
}
public void setAFF_ID(String aFF_ID) {
AFF_ID = AFF_ID;
}
public String getCH_ID() {
return CH_ID;
}
public void setCHANNEL_ID(String cH_ID) {
CH_ID = cH_ID;
}
public Long getM_ID() {
return M_ID;
}
public void setM_ID(Long m_ID) {
M_ID = m_ID;
}
public String getKEY() {
return KEY;
}
public void setKEY(String kEY) {
KEY = kEY;
}
public String getVALUE() {
return VALUE;
}
public void setVALUE(String vALUE) {
VALUE = vALUE;
}
public String getSYSTEM() {
return SYSTEM;
}
public void setSYSTEM(String sYSTEM) {
SYSTEM = sYSTEM;
}
Second entity is:
#Entity
#Table(name = "AFF")
public class AFF implements Serializable {
#Column(name = "AFF_NAME")
private String AFF_NAME;
#Column(name = "AFF_CODE")
private String AFF_CODE;
#Id
#Column(name = "AFF_ID")
private String AFF_ID;
private Set<AFF_CONFIG> someAff = new HashSet<AFF_CONFIG>();
#LazyCollection(LazyCollectionOption.TRUE)
#OneToMany(cascade = CascadeType.ALL, mappedBy = "aff")
public Set<AFF_CONFIG> getSomeAff() {
return someAff;
}
public void setSomeAff(Set<AFF_CONFIG> someAff) {
this.someAff = someAff;
}
public String getAFF_ID() {
return AFF_ID;
}
public void setAFF_ID(String aFF_ID) {
AFF_ID = aFF_ID;
}
public String getAFF_NAME() {
return AFF_NAME;
}
public void setAFF_NAME(String aFF_NAME) {
AFF_NAME = aFF_NAME;
}
public String getAFF_CODE() {
return AFF_CODE;
}
public void setAFF_CODE(String aFF_CODE) {
AFF_CODE = aFF_CODE;
}
Since this is many to one relation I created set type in one and object type in another as defined in other places.Created a repository by extending crud and added a query. Excise the bunch of different annotations, I included them in hoping to solve the null entry.
#Repository
public interface MarketRepository extends CrudRepository<AFF_CONFIG,String> {
Page<AFF_CONFIG> findAll(Pageable pageable);
#Query("Select a,b from AFF_CONFIG a, AFF b where a.AFF_ID = b.AFF_ID" )
public List<AFF_CONFIG> getAffData();
}
the applicatoin is working fine even after some tinkering until I Included these annotations. Now there is this error:
Caused by: org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: aff.
I solved the issue with the help of my Supervisor. Looks like we have to follow naming specifications for Class and variables. And one more correction is to remove collection type object and change it to just object (removed set in aff class).I will post the corrected later, to compare and contrast.
Trying to create a one to one on a table with a composite key.
I'm unable to get it to work and getting this error:
Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext-dao.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: broken column mapping for: compensation.id of: com.ciwise.model.Focus
Compensation.java:
package com.ciwise.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name = "commissions")
public class Compensation implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Composite key
*/
private CompensationPK compensationPK;
/**
* This year monthly net sales
*/
private double tYMonthlyNetSales;
/**
* Last year monthly net sales
*/
private double lYMonthlyNetSales;
/**
* This year YTD net sales
*/
private double tYYTDNetSales;
private Focus focus;
/**
* Getters and Setters
*/
#OneToOne( mappedBy = "compensation", fetch = FetchType.EAGER)
#JoinColumn(name = "FOCUS_ID")
public Focus getFocus() {
return focus;
}
public void setFocus(Focus focus) {
this.focus = focus;
}
#EmbeddedId
public CompensationPK getCompensationPK() {
return compensationPK;
}
public void setCompensationPK(CompensationPK compensationPK) {
this.compensationPK = compensationPK;
}
#Column(name = "TY_MONTHLY_NET_SALES")
public double gettYMonthlyNetSales() {
return tYMonthlyNetSales;
}
public void settYMonthlyNetSales(double tYMonthlyNetSales) {
this.tYMonthlyNetSales = tYMonthlyNetSales;
}
#Column(name = "LY_MONTHLY_NET_SALES")
public double getlYMonthlyNetSales() {
return lYMonthlyNetSales;
}
public void setlYMonthlyNetSales(double lYMonthlyNetSales) {
this.lYMonthlyNetSales = lYMonthlyNetSales;
}
#Column(name = "TY_YTD_NET_SALES")
public double gettYYTDNetSales() {
return tYYTDNetSales;
}
public void settYYTDNetSales(double tYYTDNetSales) {
this.tYYTDNetSales = tYYTDNetSales;
}
}
CompensationPK.java
package com.ciwise.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
#Embeddable
public class CompensationPK implements Serializable {
private String divisionId;
private String repId;
private int focusId;
private int repTypeId;
private int commissionYear;
private int commissionMonth;
#Column(name = "DIVISION_ID")
public String getDivisionId() {
return divisionId;
}
#Column(name = "REP_ID")
public String getRepId() {
return repId;
}
#Column(name = "FOCUS_ID")
public int getFocusId() {
return focusId;
}
#Column(name = "REPTYPE_ID")
public int getRepTypeId() {
return repTypeId;
}
#Column(name = "COMMISSION_YEAR")
public int getCommissionYear() {
return commissionYear;
}
#Column(name = "COMMISSION_MONTH")
public int getCommissionMonth() {
return commissionMonth;
}
public void setDivisionId(String divisionId) {
this.divisionId = divisionId;
}
public void setRepId(String repId) {
this.repId = repId;
}
public void setFocusId(int focusId) {
this.focusId = focusId;
}
public void setRepTypeId(int repTypeId) {
this.repTypeId = repTypeId;
}
public void setCommissionYear(int commissionYear) {
this.commissionYear = commissionYear;
}
public void setCommissionMonth(int commissionMonth) {
this.commissionMonth = commissionMonth;
}
#Override
public boolean equals(Object o) {
return false;
}
#Override
public int hashCode() {
return 0;
}
}
Focus.java:
package com.ciwise.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "CT_FOCUS")
public class Focus implements Serializable {
private int focusId;
private String focusDesc;
private String focusYN;
private Compensation compensation;
#OneToOne
#PrimaryKeyJoinColumn
public Compensation getCompensation() {
return compensation;
}
public void setCompensation(Compensation compensation) {
this.compensation = compensation;
}
public Focus() {
};
#Id
#Column(name = "FOCUS_ID")
public int getFocusId() {
return focusId;
}
public void setFocusId(int focusId) {
this.focusId = focusId;
}
#Column(name = "FOCUS_DESC", length = 16)
public String getFocusDesc() {
return focusDesc;
}
public void setFocusDesc(String focusDesc) {
this.focusDesc = focusDesc;
}
#Column(name = "FOCUS_YN", length = 1)
public String getFocusYN() {
return focusYN;
}
public void setFocusYN(String focusYN) {
this.focusYN = focusYN;
}
}
Since you used an embeddable type (CompositionPK) as your primary key for Composition entity, you should annotate the corresponding primary key field in your Composition entity with #EmbeddedId.
#EmbeddedId
private CompensationPK compensationPK;
On the Focus entity, you need not specify a #PrimaryKeyJoinColumn on the one-to-one mapping. It will just use the default join column names for the foreign keys.
So this code should be fine without the #PrimaryKeyJoinColumn:
#OneToOne
public Compensation getCompensation() {
return compensation;
}
This is a sample Hibernate generated schema based on your mappings (target DB is MySQL):
Hibernate:
create table CT_FOCUS (
FOCUS_ID integer not null,
FOCUS_DESC varchar(16),
FOCUS_YN varchar(1),
compensation_COMMISSION_MONTH integer,
compensation_COMMISSION_YEAR integer,
compensation_DIVISION_ID varchar(255),
compensation_FOCUS_ID integer,
compensation_REP_ID varchar(255),
compensation_REPTYPE_ID integer,
primary key (FOCUS_ID)
)
Hibernate:
create table commissions (
COMMISSION_MONTH integer not null,
COMMISSION_YEAR integer not null,
DIVISION_ID varchar(255) not null,
FOCUS_ID integer not null,
REP_ID varchar(255) not null,
REPTYPE_ID integer not null,
LY_MONTHLY_NET_SALES double precision,
TY_MONTHLY_NET_SALES double precision,
TY_YTD_NET_SALES double precision,
primary key (COMMISSION_MONTH, COMMISSION_YEAR, DIVISION_ID, FOCUS_ID, REP_ID, REPTYPE_ID)
)
Hibernate:
alter table CT_FOCUS
add constraint FK_d6d2c9n91dlw59uiuqswfueg5
foreign key (compensation_COMMISSION_MONTH, compensation_COMMISSION_YEAR, compensation_DIVISION_ID, compensation_FOCUS_ID, compensation_REP_ID, compensation_REPTYPE_ID)
references commissions (COMMISSION_MONTH, COMMISSION_YEAR, DIVISION_ID, FOCUS_ID, REP_ID, REPTYPE_ID)
#PrimaryKeyJoinColumn can be used on a #OneToOne mapping, if you want the primary keys of Focus entity to be referencing the primary keys of Commission entity. However, you already have defined a primary key for your Focus entity, which the focusId annotated by #Id. So there's no need to specify a #PrimaryKeyJoinColumn.
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.
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.