I have two entities: Room and Service. I also have a method in Logic class that i want to use in ServiceController class. Other classes are irrelevant.
room.getBeds() always returns 0, default int value.
Room entity:
#Entity
public class Room {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int room_id;
private int beds;
private int number;
public Room() {
}
public Room(int beds, int number) {
this.beds = beds;
this.number = number;
}
public int getRoom_id() {
return room_id;
}
public void setRoom_id(int room_id) {
this.room_id = room_id;
}
public int getBeds() {
return beds;
}
public void setBeds(int beds) {
this.beds = beds;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
Service entity:
#Entity
public class Service {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int service_id;
#JsonFormat(pattern = "dd/MM/yyyy", timezone = "Europe/Berlin")
private Date arrival_at;
#JsonFormat(pattern = "dd/MM/yyyy", timezone = "Europe/Berlin")
private Date departure_at;
private int meals;
private int guest_id;
private double price;
public int getService_id() {
return service_id;
}
public void setService_id(int service_id) {
this.service_id = service_id;
}
public Date getArrival_at() {
return arrival_at;
}
public void setArrival_at(Date arrival_at) {
this.arrival_at = arrival_at;
}
public Date getDeparture_at() {
return departure_at;
}
public void setDeparture_at(Date departure_at) {
this.departure_at = departure_at;
}
public int getMeals() {
return meals;
}
public void setMeals(int meals) {
this.meals = meals;
}
public int getGuest_id() {
return guest_id;
}
public void setGuest_id(int guest_id) {
this.guest_id = guest_id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
Service controller:
#RestController
public class ServiceController {
#Autowired
ServiceRepository serviceRepository;
private Logic logic = new Logic();
private Room room = new Room();
//CREATE
#PostMapping("/services")
public int createService(#RequestBody Service service) {
service.setPrice(logic.calculatePrice(service.getArrival_at(), service.getDeparture_at(), room.getBeds(), service.getMeals()));
return serviceRepository.save(service);
}
}
How to get the correct value from room.getBeds() getter?
Lerius you are just making a new object of Room Entity and are not populating any values from your Database to that object
that is the reason why it is taking room.getBeds(); as 0(i.e default value for int)
Try Populating DB values to your object after that you will be able to get the value of getBeds();
Related
When I am trying to implement the JPQL query, I am getting the following error,
{
"message": "could not execute query; SQL [select alerts0_.nalert_id as nalert_i1_0_, alerts0_.bis_active as bis_acti2_0_, alerts0_.dalert_date as dalert_d3_0_, alerts0_.ndept_to as ndept_to4_0_, alerts0_.ninst_to as ninst_to5_0_, alerts0_.nreceiver_id as nreceive6_0_, alerts0_.nsender_id as nsender_7_0_, alerts0_.nsubdept_to as nsubdept8_0_, alerts0_.salert_action_data as salert_a9_0_, alerts0_.salert_desc as salert_10_0_, alerts0_.salert_subject as salert_11_0_, alerts0_.salert_type as salert_12_0_ from alerts alerts0_ where alerts0_.ninst_to=?]; nested exception is org.hibernate.exception.DataException: could not execute query",
"error": "Internal Server Error",
"path": "/spacestudy/rockefeller/control/alerts/getAlertDetails"
}
And my repository query is like the following,
#Query("SELECT a FROM Alerts a")
public List<Alerts> findByAlertType();
When I hard-coded Query like #Query("SELECT a FROM Alerts a WHERE a.nreceiverId = 649"), then also getting the same error.
And I am calling this query in my service like the following:
alert= alertsRepositoryObj.findByAlertType();
And my model class Alerts.java like the following:
#Entity
#Table(name="alerts")
public class Alerts implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "alerts_seq_generator")
#SequenceGenerator(name = "alerts_seq_generator", sequenceName = "alerts_seq",allocationSize=1)
#Column(name="nalert_id",columnDefinition="serial")
public Integer nalertId;
#Column(name="salert_desc")
public String salertDesc;
#NotNull
#Column(name="nsender_id")
public Integer nsenderId;
#Column(name="dalert_date")
public LocalDate dalertDate;
#Column(name="salert_subject")
public String salertSubject;
#Column(name="salert_action_data")
public String salertActionData;
#Column(name="salert_type")
public String salertType;
#Column(name="ninst_to")
public Integer ninstTo;
#Column(name="ndept_to")
public Integer nDeptTo;
#Column(name="nsubdept_to")
public Integer nsubdeptTo;
#Column(name="nreceiver_id")
public Integer nreceiverId;
#NotNull
#Column(name="bis_active")
public Boolean bisActive=true;
#ManyToOne(optional = true)
#JoinColumn(name = "salert_action_data", insertable = false, updatable = false)
public RoomTransfer roomTransfer;
public Integer getNalertId()
{
return nalertId;
}
public void setNalertId(Integer nalertId)
{
this.nalertId = nalertId;
}
public String getSalertDesc()
{
return salertDesc;
}
public void setSalertDesc(String salertDesc)
{
this.salertDesc = salertDesc;
}
public Integer getNsenderId()
{
return nsenderId;
}
public void setNsenderId(Integer nsenderId)
{
this.nsenderId = nsenderId;
}
public LocalDate getDalertDate()
{
return dalertDate;
}
public void setDalertDate(LocalDate dalertDate)
{
this.dalertDate = dalertDate;
}
public String getSalertSubject()
{
return salertSubject;
}
public void setSalertSubject(String salertSubject)
{
this.salertSubject = salertSubject;
}
public String getSalertActionData()
{
return salertActionData;
}
public void setSalertActionData(String salertActionData)
{
this.salertActionData = salertActionData;
}
public String getSalertType()
{
return salertType;
}
public void setSalertType(String salertType)
{
this.salertType = salertType;
}
public Integer getNinstTo()
{
return ninstTo;
}
public void setNinstTo(Integer ninstTo)
{
this.ninstTo = ninstTo;
}
public Integer getnDeptTo()
{
return nDeptTo;
}
public void setnDeptTo(Integer nDeptTo)
{
this.nDeptTo = nDeptTo;
}
public Integer getNsubdeptTo()
{
return nsubdeptTo;
}
public void setNsubdeptTo(Integer nsubdeptTo)
{
this.nsubdeptTo = nsubdeptTo;
}
public Integer getNreceiverId()
{
return nreceiverId;
}
public void setNreceiverId(Integer nreceiverId)
{
this.nreceiverId = nreceiverId;
}
public Boolean getBisActive()
{
return bisActive;
}
public void setBisActive(Boolean bisActive)
{
this.bisActive = bisActive;
}
public RoomTransfer getRoomTransfer()
{
return roomTransfer;
}
public void setRoomTransfer(RoomTransfer roomTransfer)
{
this.roomTransfer = roomTransfer;
}
public Alerts()
{
super();
}
}
Why this error happening? Since this is a simple JPQL query. How can I trouble shoot the exact error here?
My entity class is here:
public class ClientDetails {
public ClientDetails() {
super();
// TODO Auto-generated constructor stub
}
#Id
#GeneratedValue
#Column(name="serialno")
public int serialno;
#Column(name="gstnum")
public int GSTnum;
#Column(name="bunk_name")
public String bunk_name;
#Column(name="mobile_num")
public int mobile_num;
#Column(name="password")
public String password;
public int getSerialno() {
return serialno;
}
public void setSerialno(int serialno) {
this.serialno = serialno;
}
public int getGSTnum() {
return GSTnum;
}
public void setGSTnum(int gSTnum) {
GSTnum = gSTnum;
}
public String getBunk_name() {
return bunk_name;
}
public void setBunk_name(String bunk_name) {
this.bunk_name = bunk_name;
}
public int getMobile_num() {
return mobile_num;
}
public void setMobile_num(int mobile_num) {
this.mobile_num = mobile_num;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
I want to select gstnum from my table based on my bunk_name.I don't want any native query like i did for gstnum in my jpa repository.
SELECT gstnum from pbm.client_details where bunk_name = 'yoga';
MY JPA REPOSITORY is
public interface ClientDetailsRepository extends JpaRepository<ClientDetails,Integer> {
public static final String gst_num = "SELECT * FROM pbm.client_details;";
//public static final String login_access = "SELECT * FROM clien_details WHERE gstnum pbm.client_details;";
#Query(value = gst_num, nativeQuery = true)
List<ClientDetails> getGstnum();
}
You could use the #Query but Spring Data would result not having too
#Query("SELECT GSTnum FROM ClientDetails where bunk_name = :callMeSomething")
List<ClientDetails> getGstnum(#Param("callMeSomething") String callMeSomething);
How a look here JPA Docs
I want to create a MongoDB collection for each month dynamically.
Example: viewLog_01_2018, viewLog_02_2018
#Document(collection = "#{viewLogRepositoryImpl.getCollectionName()}")
#CompoundIndexes({
#CompoundIndex(def = "{'viewer':1, 'viewed':1}", name = "viewerViewedIndex",unique=true)
})
public class ViewLog {
private Integer viewer;
private Integer viewed;
private Date time;
public Integer getViewer() {
return viewer;
}
public void setViewer(Integer viewer) {
this.viewer = viewer;
}
public Integer getViewed() {
return viewed;
}
public void setViewed(Integer viewed) {
this.viewed = viewed;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
}
The implementation for the collection name is as follows:
#Repository
public class ViewLogRepositoryImpl implements ViewLogRepositoryCustom {
private String collectionName;
public ViewLogRepositoryImpl() {
CommonUtility common = new CommonUtility();
Pair<Integer, Integer> pair = common.getStartingEndingDateOfMonth();
setCollectionName("viewLog_"+pair.getFirst()+"_"+pair.getSecond());
}
#Override
public String getCollectionName() {
return collectionName;
}
#Override
public void setCollectionName(String collectionName) {
this.collectionName = collectionName;
}
}
On my each request, to save a document, I am setting the collection name as:
#Autowired
ViewLogRepository viewLogRepository;
public boolean createLog(int viewer, int viewed,String viewed_mmm, Date time){
CommonUtility common = new CommonUtility();
Pair<Integer, Integer> pair = common.getStartingEndingDateOfMonth();
viewLogRepository.setCollectionName("viewLog_"+pair.getFirst()+"_"+pair.getSecond());
ViewLog viewLog = new ViewLog();
viewLog.setViewer(viewer);
viewLog.setViewed(viewed);
viewLog.setTime(time);
ViewLog viewLog2 = viewLogRepository.save(viewLog);
return true;
}
The problem I am facing is that I when for the first time I up my service the mongo collection that is created has the unique attribute for the fields 'viewer' and 'viewed' but for any subsequent collection that is created dynamically, the document does not have the unique constraint and multiple entries of same viewer-viewed combination are able to be inserted.
Any help will be very much appreciated.
I added many to many relationship to importers and agents table..data save successfully and middle table created...but i cannot retrieve data to my jsp ...How can i retrieve agents table data to my jsp.
My model is
package lk.slsi.domain;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "importers")
public class Importer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "importer_id")
private long importerId;
#NotEmpty
#Column(unique = true, nullable = false)
private String importerBrc;
private String importerVatNumber;
private String importerName;
private String importerAddress1;
private String importerAddress2;
private String importerAddress3;
private String importerCityName;
private String officePhoneNumber;
private String mobilePhoneNumber;
#Email
private String email;
#Email
private String optemail1;
#Email
private String optemail2;
public String getOptemail1() {
return optemail1;
}
public void setOptemail1(String optemail1) {
this.optemail1 = optemail1;
}
public String getOptemail2() {
return optemail2;
}
public void setOptemail2(String optemail2) {
this.optemail2 = optemail2;
}
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinTable(name = "importer_agents",
joinColumns = {#JoinColumn(name = "importerId")},
inverseJoinColumns = {#JoinColumn(name = "agentId")})
private List<Agent> agentList;
public String getImporterBrc() {
return importerBrc;
}
public void setImporterBrc(String importerBrc) {
this.importerBrc = importerBrc;
}
public String getImporterVatNumber() {
return importerVatNumber;
}
public void setImporterVatNumber(String importerVatNumber) {
this.importerVatNumber = importerVatNumber;
}
public String getImporterName() {
return importerName;
}
public void setImporterName(String importerName) {
this.importerName = importerName;
}
public String getImporterAddress1() {
return importerAddress1;
}
public void setImporterAddress1(String importerAddress1) {
this.importerAddress1 = importerAddress1;
}
public String getImporterAddress2() {
return importerAddress2;
}
public void setImporterAddress2(String importerAddress2) {
this.importerAddress2 = importerAddress2;
}
public String getImporterAddress3() {
return importerAddress3;
}
public void setImporterAddress3(String importerAddress3) {
this.importerAddress3 = importerAddress3;
}
public String getImporterCityName() {
return importerCityName;
}
public void setImporterCityName(String importerCityName) {
this.importerCityName = importerCityName;
}
public String getOfficePhoneNumber() {
return officePhoneNumber;
}
public void setOfficePhoneNumber(String officePhoneNumber) {
this.officePhoneNumber = officePhoneNumber;
}
public String getMobilePhoneNumber() {
return mobilePhoneNumber;
}
public void setMobilePhoneNumber(String mobilePhoneNumber) {
this.mobilePhoneNumber = mobilePhoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getImporterId() {
return importerId;
}
public void setImporterId(long importerId) {
this.importerId = importerId;
}
public List<Agent> getAgentList() {
return agentList;
}
public void setAgentList(List<Agent> agentList) {
this.agentList = agentList;
}
}
my agent table model is
package lk.slsi.domain;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
#Entity
#Table(name = "agents")
public class Agent {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "agent_id")
private long agentId;
#NotEmpty
#Column(unique = true, nullable = false)
private String nic;
private String vatNumber;
private String name;
private String agentAddress1;
private String agentAddress2;
private String agentAddress3;
private String agentCityName;
private String officePhoneNumber;
private String mobilePhoneNumber;
#Email
private String email;
public long getAgentId() {
return agentId;
}
public void setAgentId(long agentId) {
this.agentId = agentId;
}
public String getNic() {
return nic;
}
public void setNic(String nic) {
this.nic = nic;
}
public String getVatNumber() {
return vatNumber;
}
public void setVatNumber(String vatNumber) {
this.vatNumber = vatNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAgentAddress1() {
return agentAddress1;
}
public void setAgentAddress1(String agentAddress1) {
this.agentAddress1 = agentAddress1;
}
public String getAgentAddress2() {
return agentAddress2;
}
public void setAgentAddress2(String agentAddress2) {
this.agentAddress2 = agentAddress2;
}
public String getAgentAddress3() {
return agentAddress3;
}
public void setAgentAddress3(String agentAddress3) {
this.agentAddress3 = agentAddress3;
}
public String getAgentCityName() {
return agentCityName;
}
public void setAgentCityName(String agentCityName) {
this.agentCityName = agentCityName;
}
public String getOfficePhoneNumber() {
return officePhoneNumber;
}
public void setOfficePhoneNumber(String officePhoneNumber) {
this.officePhoneNumber = officePhoneNumber;
}
public String getMobilePhoneNumber() {
return mobilePhoneNumber;
}
public void setMobilePhoneNumber(String mobilePhoneNumber) {
this.mobilePhoneNumber = mobilePhoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
my repository is
package lk.slsi.repository;
import java.util.List;
import lk.slsi.domain.Importer;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
/**
* Created by ignotus on 2/8/2017.
*/
public interface ImporterRepository extends CrudRepository<Importer,Long> {
#Override
Importer save(Importer importer);
#Override
Importer findOne(Long importerId);
#Override
List<Importer> findAll();
#Override
void delete(Long aLong);
#Override
void delete(Importer importer);
#Override
void delete(Iterable<? extends Importer> iterable);
#Query("select u from Importer u where u.importerVatNumber = :importerVatNumber")
Importer getImporterByimporterVatNumber(#Param("importerVatNumber") String importerVatNumber);
#Query("select u from Importer u inner join u.agentList where u.importerId = :importerId")
List<Importer> findAgents(#Param("importerId") long importerId);
#Query("select u from Importer u where u.importerId = :importerId")
Importer getImporterByimporterID(#Param("importerId") long importerId);
}
my services is
public List<Importer> getAllIAgents(long importerId) {
return importerRepository.findAgents(importerId);
}
My controller is
#RequestMapping(path = "/viewImporter", method = RequestMethod.POST)
public String updateImporterAll(#RequestParam("importerId") long importerId, Model model) {
slsiLogger.info("Updating user with Id [{}]", importerId);
System.out.println("Importer id is " + importerId);
model.addAttribute("importerDetails", importerServices.getImporterByimporterID(importerId));
model.addAttribute("Agentsdetail", importerServices.getAllIAgents(importerId));
return "importerEdit";
}
Jsp is
<th width="15%">Registered Agents</th>
<c:forEach items="${Agentsdetail}" var="Agent">
<tr>
<td>${Agent.agentList.vatNumber}</td>
</tr>
/c:forEach>
</thead>
The query shows in netbeans console like this
Hibernate: select importer0_.importer_id as importer1_2_, importer0_.email as email2_2_, importer0_.importer_address1 as importer3_2_, importer0_.importer_address2 as importer4_2_, importer0_.importer_address3 as importer5_2_, importer0_.importer_brc as importer6_2_, importer0_.importer_city_name as importer7_2_, importer0_.importer_name as importer8_2_, importer0_.importer_vat_number as importer9_2_, importer0_.mobile_phone_number as mobile_10_2_, importer0_.office_phone_number as office_11_2_, importer0_.optemail1 as optemai12_2_, importer0_.optemail2 as optemai13_2_ from importers importer0_ inner join importer_agents agentlist1_ on importer0_.importer_id=agentlist1_.importer_id inner join agents agent2_ on agentlist1_.agent_id=agent2_.agent_id where importer0_.importer_id=?
How can i insert agent table values to my jsp.Please help me
I have a table that has 2 columns that create the primary key:
#Entity
#Table(name="DW.DW$SF$MONTHLY")
public class DWMonthly implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId DWMonthlyPK monthlyPK;
#Id
#Column(name="AID", insertable=false, updatable=false)
#IndexColumn(name="DW$SF$MONTHLY_PK")
private Long id;
#Column(name="CHNG_STATUS")
private BigDecimal chngStatus;
#Column(name="NAR")
private BigDecimal nar;
#Column(name="SF_AMID")
private String sfAmid;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="N_DATE", insertable=false, updatable=false)
#IndexColumn(name="DW$SF$MONTHLY_PK")
private Date nDate;
public DWMonthly() {}
public DWMonthly(Long id, String sfAmid, Date nDate) {
this.id = id;
this.sfAmid = sfAmid;
this.nDate = nDate;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public BigDecimal getChngStatus() {
return this.chngStatus;
}
public void setChngStatus(BigDecimal chngStatus) {
this.chngStatus = chngStatus;
}
public BigDecimal getNar() {
return this.nar;
}
public void setNar(BigDecimal nar) {
this.nar = nar;
}
public String getSfAmid() {
return this.sfAmid;
}
public void setSfAmid(String sfAmid) {
this.sfAmid = sfAmid;
}
public Date getNDate() {
return nDate;
}
public void setNarDate(Date nDate) {
this.nDate = nDate;
}
}
Embeddable table:
#Embeddable
public class DWMonthlyPK implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name="AID")
private long aid;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="N_DATE")
private java.util.Date nDate;
public DWMonthlyPK() {
}
public long getAid() {
return this.aid;
}
public void setAid(long aid) {
this.aid = aid;
}
public java.util.Date getNDate() {
return this.narDate;
}
public void setNDate(java.util.Date nDate) {
this.nDate = nDate;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof DWMonthlyPK)) {
return false;
}
DWMonthlyPK castOther = (DWMonthlyPK)other;
return
(this.aid == castOther.aid)
&& this.nDate.equals(castOther.nDate);
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + ((int) (this.aid ^ (this.aid >>> 32)));
hash = hash * prime + this.nDate.hashCode();
return hash;
}
}
Find the record and update:
#Repository(value="MonthlyNarDaoRepository")
#Import({JpaConfigurationImpl.class})
#Transactional(value="dwTransactionManager",readOnly = true, propagation=Propagation.REQUIRES_NEW)
public class MonthlyNarDaoImpl implements MonthlyNarDao {
#Override
#Transactional(value="dwTransactionManager")
public void findAndUpdateMonhtlyByAccountId(Map<DWAccount, UpsertResult> accountsLoadedResult) {
for (DWAccount dwAccount : accountsLoadedResult.keySet()){
try {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<DWMonthlyNar> criteriaQuery = criteriaBuilder.createQuery(DWMonthlyNar.class);
Root<DWMonthlyNar> root = criteriaQuery.from(DWMonthlyNar.class);
Predicate p = criteriaBuilder.conjunction();
p = criteriaBuilder.and(criteriaBuilder.equal(root.get("id"), dwAccount.getId()), criteriaBuilder.notEqual(root.get("nar").as(BigDecimal.class), new BigDecimal(0.0)), criteriaBuilder.isNull(root.get("sfAmid")));
criteriaQuery.select(root);
criteriaQuery.where(p);
for (DWMonthlyNar dwMonthlyNar : this.entityManager.createQuery(criteriaQuery).getResultList()){
if (dwMonthlyNar.getSfAmid()==null || !dwMonthlyNar.getSfAmid().equals(accountsLoadedResult.get(dwAccount).getId())){
dwMonthlyNar.setSfAmid(accountsLoadedResult.get(dwAccount).getId());
this.entityManager.merge(dwMonthlyNar);
}
}
} catch (Exception e) {
logger.error("MonthlyNarDaoImpl.findAndUpdateMonhtlyNarByAccountId(): " + e.getMessage());
}
}
}
}
Error:
Hibernate: update DW.DW$SF$MONTHLY set CHNG_STATUS=?, NAR=?,
SF_AMID=? where AID=? and NAR_DATE=? 16:04:58.864 [main] DEBUG
o.h.e.jdbc.spi.SqlExceptionHelper - Invalid column index [n/a]
java.sql.SQLException: Invalid column index