Persistence entities not serializable - java

I am getting following error:
SEVERE: null
javax.jms.MessageFormatException: [C4017]: Invalid message format.
at com.sun.messaging.jmq.jmsclient.MapMessageImpl.checkValidObjectType(MapMessageImpl.java:653)
at com.sun.messaging.jmq.jmsclient.MapMessageImpl.setObject(MapMessageImpl.java:632)
at buyer.Main.sendCart(Main.java:287)
after I try to send Persistence object through MapMessage in JMS system. And I am not quite sure why it happens since MapMessage accepts only serializable objects for value, and Persistence entities are serializable. I would appreciate any help! My Java code is following.
package entities;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;
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.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
#Entity
#Table(name = "carts")
#NamedQuery(
name = "carts.findAll",
query = "select c from Cart c"
)
public class Cart implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "buyer_id")
private Long buyerId;
#Column(name = "card_id")
private Long cardId;
#Column(name = "successful")
private boolean successful;
#ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
#PrimaryKeyJoinColumn(name = "buyer_id")
private Buyer buyer;
#ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
#PrimaryKeyJoinColumn(name = "card_id")
private Card card;
#OneToMany(mappedBy = "cart", cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
private List<CartItem> cartItems;
public Cart() {
}
public Cart(Long buyerId, Long cardId, boolean successful) {
this.buyerId = buyerId;
this.cardId = cardId;
this.successful = successful;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getBuyerId() {
return buyerId;
}
public void setBuyerId(Long buyerId) {
this.buyerId = buyerId;
}
public Long getCardId() {
return cardId;
}
public void setCardId(Long cardId) {
this.cardId = cardId;
}
public boolean isSuccessful() {
return successful;
}
public void setSuccessful(boolean successful) {
this.successful = successful;
}
public Buyer getBuyer() {
return buyer;
}
public void setBuyer(Buyer buyer) {
this.buyer = buyer;
}
public Card getCard() {
return card;
}
public void setCard(Card card) {
this.card = card;
}
public List<CartItem> getCartItems() {
return cartItems;
}
public void setCartItems(List<CartItem> cartItems) {
this.cartItems = cartItems;
}
#Override
public int hashCode() {
int hash = 7;
hash = 53 * hash + Objects.hashCode(this.id);
hash = 53 * hash + Objects.hashCode(this.buyerId);
hash = 53 * hash + Objects.hashCode(this.cardId);
hash = 53 * hash + (this.successful ? 1 : 0);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Cart other = (Cart) obj;
if (this.successful != other.successful) {
return false;
}
if (!Objects.equals(this.id, other.id)) {
return false;
}
if (!Objects.equals(this.buyerId, other.buyerId)) {
return false;
}
if (!Objects.equals(this.cardId, other.cardId)) {
return false;
}
return true;
}
#Override
public String toString() {
return "Cart{" + "id=" + id + ", buyerId=" + buyerId + ", cardId=" + cardId + ", successful=" + successful + '}';
}
}
Relevant method that sends message.
private static Buyer sendCart(Cart cart, String tempId, Buyer buyer) {
JMSContext context = connectionFactory.createContext(2);
try {
Destination queue = context.createQueue("mediator");
JMSProducer producer = context.createProducer();
MapMessage message = context.createMapMessage();
message.setObject("data", cart);
message.setObject("tempid", tempId);
message.setObject("type", MessageType.BUYER_SENDING_CART);
producer.send(queue, message);
} catch (JMSException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}

The Problem is the MapMessage. According to JavaDoc:
A MapMessage object is used to send a set of name-value pairs. The
names are String objects, and the values are primitive data types in
the Java programming language. The names must have a value that is not
null, and not an empty string. The entries can be accessed
sequentially or randomly by name. The order of the entries is
undefined. MapMessage inherits from the Message interface and adds a
message body that contains a Map.
And:
They may also be read or written generically as objects.
So even if MapMessage offers an "setObject" Method, the parameter used must be a primitive Type.
To pass non-primitive Types use ObjectMessage

Related

Select key from jsonb postgreSQL using Hibernate Criteria query in Java

I am writing the criteria query to get results for jsonb in postgres.I can query the jsonb column through hibernate.I am unable to fetch jsonb specific keys.I am not able to find a way.
I have tried native query but i want some wayout in hibernate criteria query.The commonjson argument is the jsonb in postgresql is this --
{"appl_id": 726516, "applied_by": "pankajkumarnnl94#gmail.com", "service_id": 9880004, "version_no": 4, "appl_ref_no": "BSEH/2018/00728", "sub_version": 1, "payment_date": "2018-12-04T11:54:20.24+05:30", "payment_mode": "PayUbizz", "reference_no": "7726929249", "service_name": "Migration Certificate Board of School Education Haryana, Bhiwani", "department_id": 784, "location_value": 1218758, "base_service_id": 988, "department_name": " Board of School Education Haryana", "registration_id": "", "submission_date": "2018-12-04", "submission_mode": "online", "no_of_attachment": 2, "submission_location": "1578947~1218758~Board of School Education Haryana"}
Model Class ->ApplInfoJson
package com.saral.reporting.model;
import java.util.Map;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Type;
import com.fasterxml.jackson.annotation.JsonProperty;
#Entity
#Table(name = "r_app_json",schema="saral1", catalog="saral1")
public class ApplInfoJson {
#Id
#Column(name = "aid")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long aid;
#Column(name = "id")
private Long id;
#JsonProperty("appl_info")
#Column(name = "appl_info")
private String applInfo;
#Column(name = "application_form_attributes")
private String applicationFormAttributes;
#Column(name = "enclosure_data")
private String enclosureData;
#Column(name = "service_id")
private Long serviceId;
#Column(name = "combined_json")
#Type(type = "JsonDataUserType")
private Map<String , Object> combinedJson;
#Column(name ="location_value")
private Long locationValue;
public Long getLocationValue() {
return locationValue;
}
public void setLocationValue(Long locationValue) {
this.locationValue = locationValue;
}
public Long getServiceId() {
return serviceId;
}
public void setServiceId(Long serviceId) {
this.serviceId = serviceId;
}
public Long getAid() {
return aid;
}
public void setAid(Long aid) {
this.aid = aid;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getApplInfo() {
return applInfo;
}
public void setApplInfo(String applInfo) {
this.applInfo = applInfo;
}
public String getApplicationFormAttributes() {
return applicationFormAttributes;
}
public void setApplicationFormAttributes(String applicationFormAttributes) {
this.applicationFormAttributes = applicationFormAttributes;
}
public String getEnclosureData() {
return enclosureData;
}
public void setEnclosureData(String enclosureData) {
this.enclosureData = enclosureData;
}
public Map<String, Object> getCombinedJson() {
return combinedJson;
}
public void setCombinedJson(Map<String, Object> combinedJson) {
this.combinedJson = combinedJson;
}
#Override
public String toString() {
return "ApplInfoJson [aid=" + aid + ", id=" + id + ", applInfo=" + applInfo + ", applicationFormAttributes="
+ applicationFormAttributes + ", enclosureData=" + enclosureData + ", serviceId=" + serviceId
+ ", combinedJson=" + combinedJson + ", locationValue=" + locationValue + "]";
}
}
Function Used->
public List<ApplInfoJson> findByCombinedJson(String commonJson) {
DetachedCriteria criteria = DetachedCriteria.forClass(ApplInfoJson.class);
List<ApplInfoJson> results = (List<ApplInfoJson>) getHibernateTemplate().findByCriteria(criteria);
return results;
}
I want some thing to pass key name and get data with specific key.

Join two tables on basis of One common column via Hibernate Annotation and JPA criteria Query not working as expected

I have two tables device_data and device_connection. I want to join these two tables on basis of column customerId. Both the tables have customerId column.
DeviceData
import java.io.Serializable;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "device_data")
public class DeviceData implements Serializable,Cloneable {
#Id
#Column(name = "identifier")
private BigInteger identifier;
#Id
#Column(name = "device_time")
private Timestamp deviceTime;
#Column(name = "ctr_id")
private BigInteger customerId;
#Column(name = "signal_strength")
private Double signalStrength;
#OneToOne
#JoinColumn(name = "ctr_id", nullable = false, insertable = false, updatable = false, referencedColumnName = "ctr_id")
private DeviceConnection deviceConnection;
public BigInteger getIdentifier() {
return identifier;
}
public DeviceData setIdentifier(BigInteger identifier) {
this.identifier = identifier;
return this;
}
public Timestamp getDeviceTime() {
return deviceTime;
}
public DeviceData setDeviceTime(Timestamp deviceTime) {
this.deviceTime = deviceTime;
return this;
}
public BigInteger getCustomerId() {
return customerId;
}
public DeviceData setCustomerId(BigInteger customerId) {
this.customerId = customerId;
return this;
}
public DeviceConnection getDeviceConnection() {
return deviceConnection;
}
public DeviceData setDeviceConnection(
DeviceConnection deviceConnection) {
this.deviceConnection = deviceConnection;
return this;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DeviceData that = (DeviceData) o;
return identifier.equals(that.identifier) &&
deviceTime.equals(that.deviceTime);
}
#Override
public int hashCode() {
return Objects.hash(identifier, deviceTime);
}
}
DeviceConnection
import java.io.Serializable;
import java.math.BigInteger;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name = "device_connection")
public class DeviceConnection implements Serializable , Cloneable {
public DeviceConnection() {
}
#Column(name = "id")
private BigInteger id;
#Column(name = "ctr_id")
private BigInteger customerId;
#Column(name = "low_signal_strength_limit")
private Integer lowSignalStrengthLimit;
public BigInteger getCustomerId() {
return customerId;
}
public DeviceConnection setCustomerId(BigInteger customerId) {
this.customerId = customerId;
return this;
}
public Integer getLowSignalStrengthLimit() {
return lowSignalStrengthLimit;
}
public DeviceConnection setLowSignalStrengthLimit(
Integer lowSignalStrengthLimit) {
this.lowSignalStrengthLimit = lowSignalStrengthLimit;
return this;
}
public BigInteger getId() {
return id;
}
public DeviceConnection setId(BigInteger id) {
this.id = id;
return this;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DeviceConnection that = (DeviceConnection) o;
return Objects.equals(getId(), that.getId());
}
#Override
public int hashCode() {
return Objects.hash(getId());
}
}
I wrote a Query to get data from join of these two tables.
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<DeviceData> cq = cb.createQuery(DeviceData.class);
Root<DeviceData> root = cq.from(DeviceData.class);
Join<DeviceData, DeviceConnection> join = (Join<DeviceData, DeviceConnection>) root
.fetch(DeviceData_.deviceConnection);
List<Predicate> conditions = new ArrayList<>();
conditions.add(cb.equal(root.get(DeviceData_.CUSTOMER_ID), join.get(
DeviceConnection_.CUSTOMER_ID)));
conditions.add(cb.greaterThanOrEqualTo(root.get(DeviceData_.DEVICE_TIME),
config.getDataStartTime()));
if (isNotNull(config.getDataEndTime())) {
conditions.add(cb.lessThanOrEqualTo(root.get(DeviceData_.DEVICE_TIME),
config.getDataEndTime()));
}
cq.where(conditions.toArray(new Predicate[]{}))
.orderBy(cb.asc(root.get(DeviceData_.DEVICE_TIME)));
return session.createQuery(cq);
And I set the property SHOW_SQL to TRUE. So, here is the query which hibernate generate.
select
devicedata0_.occurrence_time as occurren1_3_0_, devicedata0_.identifier as identifier2_3_0_, connection1_.id as id1_0_1_, devicedata0_.ctr_id as ctr_id9_3_0_, devicedata0_.signal_strength as signal_15_3_0_, connection1_.ctr_id as ctr_id7_0_1_, connection1_.low_signal_strength_limit as low_sig14_0_1_
from
device_data devicedata0_
inner join device_connection connection1_ on
devicedata0_.ctr_id=connection1_.ctr_id
where
devicedata0_.ctr_id=connection1_.ctr_id and
devicedata0_.created_at>='2018-06-12 12:00:00'
order by
devicedata0_.created_at asc
limit 2000;
when i run this Query on My Sql workbench it will work expected and give me results. But hibernate constantly giving me exception i don't know why?
Exception
java.lang.ClassCastException: com.sbi.model.DeviceConnection cannot be cast to java.math.BigInteger

Hibernate error: found shared references

Request processing failed; nested exception is
org.springframework.orm.hibernate5.HibernateSystemException: Found
shared references to a collection:
sabeja.entity.ClassificatorObject.apartmentPayers; nested exception is
org.hibernate.HibernateException: Found shared references to a
collection: sabeja.entity.ClassificatorObject.apartmentPayers
I have been searching solution for 2 days. I found solutions in the stackoverflow, but they didn't help for me. I disabled parts of code, but I haven't caught problem.
ClassificatorObject Entity
package xm.entity;
import java.io.Serializable;
import java.util.Set;
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.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.OrderBy;
import javax.persistence.Table;
#Entity
#Table(name="managment_responsibilities_object")
public class ClassificatorObject implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="responsibility_id")
private int responsibilityId;
#Column(name="object_id")
private int objectId;
#Column(name="is_enabled")
private int isEnabled;
#Column(name="by_area")
private int byArea;
#Column(name="by_people")
private int byPeople;
#Column(name="by_flat")
private int byFlat;
#Column(name="is_general")
private int isGeneral;
#Column(name="sort")
private int sort;
#Column(name="not_counting")
private int notCounting;
// #OneToMany(fetch = FetchType.LAZY, mappedBy = "classificatorObject", cascade = CascadeType.ALL)
// #OrderBy("month")
// private Set<ServicePeriod> periods;
#OneToMany(fetch = FetchType.LAZY)
#JoinColumn(name = "service_id", insertable=false, updatable=false)
private Set<ServiceOption> options;
#OneToMany(fetch = FetchType.LAZY)
//#JoinColumn(name = "service_id", insertable=false, updatable=false)
#JoinColumn(
name = "object_id",
referencedColumnName = "object_id",
insertable=false, updatable=false
)
private Set<ApartmentPayer> apartmentPayers;
public Set<ApartmentPayer> getApartmentPayers() {
return apartmentPayers;
}
public void setApartmentPayers(Set<ApartmentPayer> apartmentPayers) {
this.apartmentPayers = apartmentPayers;
}
#Column(name="parent_service_id")
private int parentServiceId;
#Column(name="has_children")
private int hasChildren;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name="responsibility_id", insertable=false, updatable=false)
private Classificator classificator;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name="parent_service_id", insertable=false, updatable=false)
private ClassificatorObject parentService;
//CONSTRUCTORS:
public ClassificatorObject() {
}
public ClassificatorObject(int responsibilityId, int objectId, int isEnabled, int byArea, int byPeople, int byFlat,
int isGeneral, int sort, int notCounting, Set<ServicePeriod> periods, Set<ServiceOption> options,
int parentServiceId, int hasChildren, Classificator classificator) {
super();
this.responsibilityId = responsibilityId;
this.objectId = objectId;
this.isEnabled = isEnabled;
this.byArea = byArea;
this.byPeople = byPeople;
this.byFlat = byFlat;
this.isGeneral = isGeneral;
this.sort = sort;
this.notCounting = notCounting;
// this.periods = periods;
this.options = options;
this.parentServiceId = parentServiceId;
this.hasChildren = hasChildren;
this.classificator = classificator;
}
//GETTERS SETTERS:
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getResponsibilityId() {
return responsibilityId;
}
public void setResponsibilityId(int responsibilityId) {
this.responsibilityId = responsibilityId;
}
public int getObjectId() {
return objectId;
}
public void setObjectId(int objectId) {
this.objectId = objectId;
}
public int getIsEnabled() {
return isEnabled;
}
public void setIsEnabled(int isEnabled) {
this.isEnabled = isEnabled;
}
public int getByArea() {
return byArea;
}
public void setByArea(int byArea) {
this.byArea = byArea;
}
public int getByPeople() {
return byPeople;
}
public void setByPeople(int byPeople) {
this.byPeople = byPeople;
}
public int getByFlat() {
return byFlat;
}
public void setByFlat(int byFlat) {
this.byFlat = byFlat;
}
public int getIsGeneral() {
return isGeneral;
}
public void setIsGeneral(int isGeneral) {
this.isGeneral = isGeneral;
}
public int getSort() {
return sort;
}
public void setSort(int sort) {
this.sort = sort;
}
public int getNotCounting() {
return notCounting;
}
public void setNotCounting(int notCounting) {
this.notCounting = notCounting;
}
// public Set<ServicePeriod> getPeriods() {
// return periods;
// }
//
// public void setPeriods(Set<ServicePeriod> periods) {
// this.periods = periods;
// }
public Set<ServiceOption> getOptions() {
return options;
}
public void setOptions(Set<ServiceOption> options) {
this.options = options;
}
public int getParentServiceId() {
return parentServiceId;
}
public void setParentServiceId(int parentServiceId) {
this.parentServiceId = parentServiceId;
}
public int getHasChildren() {
return hasChildren;
}
public void setHasChildren(int hasChildren) {
this.hasChildren = hasChildren;
}
public Classificator getClassificator() {
return classificator;
}
public void setClassificator(Classificator classificator) {
this.classificator = classificator;
}
public ClassificatorObject getParentService() {
return parentService;
}
public void setParentService(ClassificatorObject parentService) {
this.parentService = parentService;
}
#Override
public String toString() {
return "ClassificatorObject [id=" + id + ", responsibilityId=" + responsibilityId + ", objectId=" + objectId
+ ", isEnabled=" + isEnabled + ", byArea=" + byArea + ", byPeople=" + byPeople + ", byFlat=" + byFlat
+ ", isGeneral=" + isGeneral + ", sort=" + sort + ", notCounting=" + notCounting + ", parentServiceId="
+ parentServiceId + ", hasChildren=" + hasChildren + "]";
}
}
ApartmentPayer Entity
package sabeja.entity;
import java.math.BigDecimal;
import java.util.Set;
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.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="sb_flat_payers")
public class ApartmentPayer {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Integer id;
#Column(name="flat_id")
private int flatId;
#Column(name="payer_id")
private int payerId;
#Column(name="object_id")
private int objectId;
#Column(name="area", columnDefinition="Decimal(12,2)")
private BigDecimal area;
#Column(name="people_number")
private int peopleNumber;
#OneToMany(fetch = FetchType.LAZY)
#JoinColumn(name="flatPayer_id", insertable=false, updatable=false)
private Set<ServiceOption> options;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name="payer_id", insertable= false, updatable= false)
private User user;
// #ManyToOne(fetch = FetchType.LAZY)
// #JoinColumn(name="object_id", insertable=false, updatable=false)
// private TheObject theObject;
public ApartmentPayer() {
super();
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Set<ServiceOption> getOptions() {
return options;
}
public void setOptions(Set<ServiceOption> options) {
this.options = options;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public int getFlatId() {
return flatId;
}
public void setFlatId(int flatId) {
this.flatId = flatId;
}
public int getPayerId() {
return payerId;
}
public void setPayerId(int payerId) {
this.payerId = payerId;
}
public BigDecimal getArea() {
return area;
}
public void setArea(BigDecimal area) {
this.area = area;
}
public int getPeopleNumber() {
return peopleNumber;
}
public void setPeopleNumber(int peopleNumber) {
this.peopleNumber = peopleNumber;
}
public int getObjectId() {
return objectId;
}
public void setObjectId(int objectId) {
this.objectId = objectId;
}
// public TheObject getTheObject() {
// return theObject;
// }
//
//
//
// public void setTheObject(TheObject theObject) {
// this.theObject = theObject;
// }
#Override
public String toString() {
return "ApartmentPayer [id=" + id + ", flatId=" + flatId + ", payerId=" + payerId + ", area=" + area
+ ", peopleNumber=" + peopleNumber + "]";
}
}
DAOIMPL
Query<Apartment> queryResult2 = currentSession
.createQuery("SELECT DISTINCT a FROM Apartment a "
+ "JOIN FETCH a.theObject o "
+ "JOIN FETCH o.services s "
+ "JOIN FETCH s.apartmentPayers ap "
// + "LEFT JOIN FETCH s.options op "
// + "JOIN ServicePeriod p ON s.id = p.responsibilities_object_id "
// + "JOIN FETCH ap.user u "
+ "WHERE a.houseId = :object_id "
// + "AND (op.flatPayerId = ap.id OR op.id is NULL) "
//+ "AND (SELECT count(*) FROM DisabledPayer di WHERE di.serviceId = s.id AND di.flatPayerId = ap.id) = 0"
// + "AND (CASE WHEN op.is_disabled = 0 THEN 1 WHEN op.is_disabled = 1 "
// + "THEN 0 END) = 1) OR op.id IS NULL"
, Apartment.class);
This error can happen in some specific cases when you have kind of a 'loop' reference, but in this case you don't have a class with a field that uses this same class.
So the error has to be in a call to the method setApartmentPayers(), you need to check all the calls to the method and ensure that you are not assigning the same collection to two different entities.

Datepick 1 day before Angularjs

Im having trouble making the datepicker( angularjs-datepicker 720kb.datepicker), it keeps returning dates 1 day before of what it should.
<div class="col-md-5">
<label>Fecha Disposicion</label>
<datepicker date-format="yyyy-MM-dd" date-year-title="selected year">
<input ng-model="vm.auto.fechaDisposicion" />
</datepicker>
</div>
Im using UTC time for the rest of my app, and the back end is springboot data rest and the database mysql (datetime).
Here's the suggested workaround in the git hub proyect, but I don't really get how to implement it.
Output before POST method: "2018-01-03"
Arrives at the DB like this: "2018-01-02 00:00:00"
MY java controller:
package ar.gob.snr.expediente.domain;
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.springframework.data.rest.core.annotation.RestResource;
#Entity
#Table(name = "auto")
public class Auto implements Serializable {
private static final long serialVersionUID = -4601105083604023376L;
#Id
#GeneratedValue(strategy = javax.persistence.GenerationType.IDENTITY )
#Column(name = "id")
private Long id;
#Column(name = "expediente_1")
private String expediente1;
#Column(name = "expediente_2")
private String expediente2;
#Column(name = "expediente_3")
private String expediente3;
#Column(name = "expediente_4")
private String expediente4;
#Column(name = "expediente_5")
private String expediente5;
#RestResource(exported = false)
#ManyToOne(cascade = CascadeType.MERGE, fetch= FetchType.EAGER)
#JoinColumn(name = "tipo_documento", referencedColumnName = "id")
private TipoDocumento tipoDocumento;
#Column(name = "numero_documento")
private Integer numeroDocumento;
#Column(name = "auto")
private String auto;
#Column(name = "patente")
private String patente;
#Column(name = "fecha_simbolo")
private Date fechaSimbolo;
#Column(name = "fecha_disposicion")
private Date fechaDisposicion;
#Column(name = "nro_disposicion")
private Integer nroDisposicion;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public TipoDocumento getTipoDocumento() {
return tipoDocumento;
}
public void setTipoDocumento(TipoDocumento tipoDocumento) {
this.tipoDocumento = tipoDocumento;
}
public Integer getNumeroDocumento() {
return numeroDocumento;
}
public void setNumeroDocumento(Integer numeroDocumento) {
this.numeroDocumento = numeroDocumento;
}
public String getExpediente1() {
return expediente1;
}
public void setExpediente1(String expediente1) {
this.expediente1 = expediente1;
}
public String getExpediente2() {
return expediente2;
}
public void setExpediente2(String expediente2) {
this.expediente2 = expediente2;
}
public String getExpediente3() {
return expediente3;
}
public void setExpediente3(String expediente3) {
this.expediente3 = expediente3;
}
public String getExpediente4() {
return expediente4;
}
public void setExpediente4(String expediente4) {
this.expediente4 = expediente4;
}
public String getExpediente5() {
return expediente5;
}
public void setExpediente5(String expediente5) {
this.expediente5 = expediente5;
}
public String getAuto() {
return auto;
}
public void setAuto(String auto) {
this.auto = auto;
}
public String getPatente() {
return patente;
}
public void setPatente(String patente) {
this.patente = patente;
}
public Date getFechaSimbolo() {
return fechaSimbolo;
}
public void setFechaSimbolo(Date fechaSimbolo) {
this.fechaSimbolo = fechaSimbolo;
}
public Date getFechaDisposicion() {
return fechaDisposicion;
}
public void setFechaDisposicion(Date fechaDisposicion) {
this.fechaDisposicion = fechaDisposicion;
}
public Integer getNroDisposicion() {
return nroDisposicion;
}
public void setNroDisposicion(Integer nroDisposicion) {
this.nroDisposicion = nroDisposicion;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Auto other = (Auto) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}

EclipseLink EntityManager SQL JOIN on two tables

I have 2 different tables: subjects and questions and I need to make SQL JOIN on these 2 tables. Table subjects has its attributes: name and shortcut. Table questions has its attributes: question_number, text, subject - in fact, subject from table questions is a shortcut of a subject.
I tried something like this, what I saw in one stackoverflow topic:
Query q = em.createNativeQuery("SELECT q.question_number, q.text, s.name, s.shortcut FROM "
+ "( questions q INNER JOIN subjects s ON q.subject=s.shortcut );", QuestionSubject.class);
QuestionSubject.class is an #Entity class and has attributes of both questions table and subjects table. After calling this method I saw that a new table with a name QUESTIONSUBJECT was created in my database and that is what I do not want to be done.
Can anyone help me with other solution?
P.S.: I am doing this in order to use the ouput as a response on HTTP request so I need to gather those two into one. I need to return either a List or JSON string.
EDIT: Using MySQL database.
questions table Entity class:
package model;
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.Table;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "questions")
#XmlRootElement
public class Question implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Basic(optional = false)
#Column(name = "question_number")
private Integer questionNumber;
#Column(name = "text")
private String text;
#Column(name = "subject")
private String subject;
public Question() {
}
public Question(Integer questionNumber) {
this.questionNumber = questionNumber;
}
public Question( String text, String subject) {
this.text = text;
this.subject = subject;
}
public Question(Integer questionNumber, String text, String subject) {
this.questionNumber = questionNumber;
this.text = text;
this.subject = subject;
}
public Integer getQuestionNumber() {
return questionNumber;
}
public void setQuestionNumber(Integer questionNumber) {
this.questionNumber = questionNumber;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
#Override
public int hashCode() {
int hash = 0;
hash += (questionNumber != null ? questionNumber.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 Question)) {
return false;
}
Question other = (Question) object;
if ((this.questionNumber == null && other.questionNumber != null) || (this.questionNumber != null && !this.questionNumber.equals(other.questionNumber))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Rest.Questions[ questionNumber=" + questionNumber + " ]";
}
}
subjects table Entity class.
package model;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "subjects")
#XmlRootElement
public class Subject implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 5)
#Column(name = "shortcut")
private String shortcut;
#Basic(optional = false)
#NotNull
#Lob
#Size(min = 1, max = 65535)
#Column(name = "name")
private String name;
public Subject() {
}
public Subject(String shortcut) {
this.shortcut = shortcut;
}
public Subject(String shortcut, String name) {
this.shortcut = shortcut;
this.name = name;
}
public String getShortcut() {
return shortcut;
}
public void setShortcut(String shortcut) {
this.shortcut = shortcut;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public int hashCode() {
int hash = 0;
hash += (shortcut != null ? shortcut.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 Subject)) {
return false;
}
Subject other = (Subject) object;
if ((this.shortcut == null && other.shortcut != null) || (this.shortcut != null && !this.shortcut.equals(other.shortcut))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Rest.Subjects[ shortcut=" + shortcut + " ]";
}
}
QuestionSubject Entity class:
package model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class QuestionSubject implements Serializable
{
#Id
#Column(name = "question_number")
private Integer questionNumber;
#Column(name = "text")
private String text;
#Column(name = "shortcut")
private String shortcut;
#Column(name = "name")
private String name;
public Integer getQuestionNumber() {
return questionNumber;
}
public void setQuestionNumber(Integer questionNumber) {
this.questionNumber = questionNumber;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getShortcut() {
return shortcut;
}
public void setShortcut(String shortcut) {
this.shortcut = shortcut;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The table gets created because you define a class named QuestionSubject annotated as #Entity. Per default the table name is the class name.
You could override the name like you did in Subjects with #Table(name = "subjects")
Nearly the same would happen if you would define a #ManyToMany mapping on related fields between classes Question and Subject without defining QuestionSubject class at all.
I would recommend to take a look here to get more information:
http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Mapping/Relationship_Mappings/Collection_Mappings/ManyToMany
Edit
If you need a manyToMany mapping you need this table. Otherwise you can only have an oneToMany resp. manyToOne relation (using foreign keys).

Categories