I have class same this:
public class DoctorCalender {
private Long reservationId;
private Date reservationDate;
private String hospitalName;
private String roomName;
private Long capacityId;
private List<Shift> shifts = new ArrayList<>();
. . .
public List<Shift> getShifts() {
return shifts;
}
public void setShifts(List<Shift> shifts) {
this.shifts = shifts;
}
}
and I'm going to hql export mapping to above class with use this method:
.setResultTransformer(Transformers.aliasToBean(DoctorCalender.class))
and I get this error :
IllegalArgumentException occurred while calling setter for property [ir.sayar.hospital.toolBox.helperClass.DoctorCalender.shifts (expected type = java.util.List)]
Related
I want to store a List of class : RestApiResponse into MySql. But getting below error:
org.hibernate.HibernateException: Could not determine a type for class: com.try.sreapi.beans.RestApiResponse
Below are my classes:
Entity class : SREAPITestingHistory.java
#NamedQueries(#NamedQuery(name="getSREAPITestHistory.findAll", query="SELECT a FROM SREAPITestingHistory a"))
#SqlResultSetMapping(name="sreapitestinghistoryres",
entities=#EntityResult(entityClass=SREAPITestingHistory.class))
#Entity
#Table(name="sreapi_testing_history_details")
#Transactional
public class SREAPITestingHistory implements Serializable{
private static final long serialVersionUID = -7221709766109001257L;
#Id
#Column(name="request_time")
private String request_time;
#Column(name="req_id")
private String req_id;
#Column(name="app_name")
private String app_name;
#Column(name="request_name")
private String request_name;
#Lob
#Column(name="response_body")
private List<RestApiResponse> response;
public String getRequest_time() {
return request_time;
}
public void setRequest_time(String request_time) {
this.request_time = request_time;
}
public String getReq_id() {
return req_id;
}
public void setReq_id(String req_id) {
this.req_id = req_id;
}
public String getApp_name() {
return app_name;
}
public void setApp_name(String app_name) {
this.app_name = app_name;
}
public String getRequest_name() {
return request_name;
}
public void setRequest_name(String request_name) {
this.request_name = request_name;
}
public List<RestApiResponse> getResponse() {
return response;
}
public void setResponse(List<RestApiResponse> response) {
this.response = response;
}
}
Repository Class: SREAPITestingRepository.java
#Repository
public interface SREAPITestingRepository extends CrudRepository< SREAPITestingHistory, String> {
#Modifying
#Transactional
#Query(value="INSERT into sreapi_testing_history_details (request_time,req_id,app_name,request_name,response_body)"+ "VALUES (:request_time,:req_id,:app_name,:request_name,:response_body)", nativeQuery = true)
public void setApiTestHistoryDetails(#Param("request_time") String request_time,#Param("req_id") String req_id,#Param("app_name") String app_name,#Param("request_name") String request_name,#Param("response_body") List<RestApiResponse> response_body);
}
When I am trying to add values for response_body which is actually a List of RestApiResponse class and I am getting Could not determine a type for class: com.try.sreapi.beans.RestApiResponse exception
From Official doc
A Lob may be either a binary or character type.
The Lob type is inferred from the type of the persistent field or
property, and except for string and character-based types defaults to
Blob.
Example 1:
#Lob #Basic(fetch=LAZY) #Column(name="REPORT")
String report;
Example 2:
#Lob #Basic(fetch=LAZY) #Column(name="EMP_PIC",
columnDefinition="BLOB NOT NULL") protected byte[] pic;
So you can convert your list of data into json string or bytes to store.
I have a simple server reads all logs from mongodb, but some data in the db has different format for their result property.
one is whose result property has a value like a hashmap:
{
"event_name" : "Transfer",
"result" : { "_from" : "0x928c9af0651632157ef27a2cf17ca72c575a4d21",
"_value" : "1111",
"_to" :"0x143449e55cdd2a5bae081f041650ba9089812a95" },
"transaction_id":"c2c986a96a0cfa7fc96619733449fd88c9d685bf704a50d07baef74f6
}
then for the result property, it returns an empty result for me,
but if the result property is like this, which is just like an array:
"result" : ["0x928c9af0651632157ef27a2cf17ca72c575a4d21", "1111", "0x143449e55cdd2a5bae081f041650ba9089812a95"],
then it will outputs the result value.
The thing is it has both format in the mongodb, is there any way to handle both of the 2 different format of result property?
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
#Document(collection = "eventLog")
public class EventLogEntity implements Serializable {
private static final long serialVersionUID = -70777625567836430L;
#Id
private String id;
#Field(value = "block_number")
#JsonProperty(value = "block_number")
private long blockNumber;
#Field(value = "block_timestamp")
#JsonProperty(value = "block_timestamp")
private long blockTimestamp;
#Field(value = "contract_address")
#JsonProperty(value = "contract_address")
private String contractAddress;
#Field(value = "event_name")
#JsonProperty(value = "event_name")
private String entryName;
#Field(value = "result")
#JsonProperty(value = "result")
private JSONArray resultJsonArray;
#Field(value = "transaction_id")
#JsonProperty(value = "transaction_id")
private String transactionId;
public EventLogEntity(long blockNumber, long blockTimestamp, String contractAddress,
String entryName, JSONArray resultJsonArray, String transactionId) {
this.blockNumber = blockNumber;
this.blockTimestamp = blockTimestamp;
this.contractAddress = contractAddress;
this.entryName = entryName;
this.resultJsonArray = resultJsonArray;
this.transactionId = transactionId;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public long getBlockNumber() {
return blockNumber;
}
public void setBlockNumber(long blockNumber) {
this.blockNumber = blockNumber;
}
public long getBlockTimestamp() {
return blockTimestamp;
}
public void setBlockTimestamp(long blockTimestamp) {
this.blockTimestamp = blockTimestamp;
}
public String getContractAddress() {
return contractAddress;
}
public void setContractAddress(String contractAddress) {
this.contractAddress = contractAddress;
}
public String getEntryName() {
return entryName;
}
public void setEntryName(String entryName) {
this.entryName = entryName;
}
public JSONArray getResultJsonArray() {
System.out.println(resultJsonArray.toString());
return resultJsonArray;
}
public void setResultJsonArray(JSONArray resultJsonArray) {
this.resultJsonArray = resultJsonArray;
}
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
}
First of all, you have 2 different documents entities, if you really need keep both formats and read one or other, you should one have Entity for each structure.
One entity will be as you described, and the other will have the result property as follows:
public class ResultObject{
private String _from;
private String _value;
private String _to;
//getters, setters & constructor
}
And you reference this ResultObject as property of your other Entity:
public class EventLogEntityWithResultObject implements Serializable{
...
private ResultObject result;
...
}
If you do not need to keep both structures, you could migrate all documents from one structure type to another using MongoDB commands, see this for example: Change document structure in mongodb with the mongo shell
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.
I have a Problem with Spring - Data - Redis
I am using redis as cache for entities that i am fetching from database using JPA Repository.
Here is the entity structure :
#Entity(name = "issue_category")
public class IssueCategory extends AuditablePersistable {
private static final long serialVersionUID = 8659360844089652714L;
private Integer parentId;
private String name;
private String displayNameCRM;
private String displayNameSelfServe;
private List<IssueCategoryRule> issueCategoryRules = new ArrayList<>();
public static final Integer ROOT_PARENT_ID = 0;
// with all getter setters
}
Here is part where i am caching it:
#Override
#Cacheable(value = IC_CACHE, key = "#id")
public IssueCategory getIssueCategoriesById(Integer id) {
return issueCategoriesRepo.findById(id);
}
The Repo code for getting from db:
public interface IssueCategoryRepo extends JpaRepository<IssueCategory, Integer>
{
public IssueCategory findByName(#Param("name") String name);
public List<IssueCategory> findByParentId(#Param("parentId") Integer parentId);
public IssueCategory findById(#Param("id") Integer id);
}
The problem I am getting is
Class Cast exception when this entity is being extracted from cache
It says :
Can not cast from java.util.ArrayList to IssueCategory class.
Can anybody help.
I have an Entity Campaign that has a OneToOne relationship with CampaignCities cities.
In turn, CampaignCities contains a Set cities;
The campaign entity
#Entity
#javax.persistence.Table(uniqueConstraints={#UniqueConstraint(columnNames={"name","company_id"}), #UniqueConstraint(columnNames={"id"})})
public class Campaign implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Long id;
#NotEmpty
#Size(min=1, max=100)
private String name;
private Date startDate;
private Date endDate;
#Valid
private Deal deal;
#Valid
private Company company;
#OneToOne
private CampaignCities cities = new CampaignCities();
The CampaignCities entity
#Entity
public class CampaignCities {
private long id;
private Set<City> cities = new HashSet<City>();
#Id
#javax.persistence.GeneratedValue(strategy=GenerationType.AUTO)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#OneToMany
public Set<City> getCities() {
return cities;
}
public void setCities(Set<City> cities) {
this.cities = cities;
}
}
The City entity:
#Entity
public class City implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private Long id;
#javax.persistence.Id
#javax.persistence.GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
My NewCampaignController
#SessionAttributes(value={"campaign", "campaignCities"})
#Controller
public class NewCampaignController {
//private static final Logger logger = LoggerFactory.getLogger(NewDealController.class);
#Autowired
private CampaignManager campaignManager;
#Autowired
private CityManager cityManager;
#Autowired
SimpleDateFormat dateFormat;
#Autowired
CustomDateEditor dateEditor;
#RequestMapping(value = "campaign/new", method = RequestMethod.GET)
public String showForm(Map<String, Object> model) {
//List<Campaign> campaigns = campaignManager.getCampaigns();
Campaign campaignForm = new Campaign();
CampaignCities cities = new CampaignCities();
cities.setCities(new HashSet<City>(cityManager.getCity()));
//campaignForm.setCities(cities);
model.put("campaignCities", cities);
model.put("campaign", campaignForm);
return "campaign/new";
}
#RequestMapping(value = "campaign/new", method = RequestMethod.POST)
public String processForm(#Valid Campaign campaignForm, BindingResult result, Map<String,Object> model) {
new CampaignValidator().validate(campaignForm, result);
if (result.hasErrors()) {
return "campaign/new";
}
this.campaignManager.saveCampaign(campaignForm);
model.put("campaign", campaignForm);
model.put("campaigns", this.campaignManager.getCampaigns());
return "campaign/added";
}
I have been able to get campaign to render in a form and I've rendered the list of cities successfully using:
<form:checkboxes items="${campaignCities.cities}" path="cities" itemLabel="name" itemValue="id" delimiter="<br/>" />
However when i submit the form, I get the following validation error.
Field error in object 'campaign' on field 'cities': rejected value
[2,1]; codes
[typeMismatch.campaign.cities,typeMismatch.cities,typeMismatch.com.groupdealclone.app.domain.CampaignCities,typeMismatch];
arguments
[org.springframework.context.support.DefaultMessageSourceResolvable:
codes [campaign.cities,cities]; arguments []; default message
[cities]]; default message [Failed to convert property value of type
'java.lang.String[]' to required type
'com.groupdealclone.app.domain.CampaignCities' for property 'cities';
nested exception is java.lang.IllegalStateException: Cannot convert
value of type [java.lang.String[]] to required type
[com.groupdealclone.app.domain.CampaignCities] for property 'cities':
no matching editors or conversion strategy found]
I've tried to figure out a way to handle this in SpringMVC 3 but I've been stuck for over a day with no success. I simply want a List or Set or Cities that where checked on the form to be submitted to the controller and added to the Campaign. How do I get around the conversion problem where I can convert the String[] returned to a List or Set of Cities.
The project I'm working on is a public GitHub project, you can download the source and set it up using Maven if you like the project is called Group-Deal-Clone
After what is almost 2 days, the answer was simpler than I expected. Thanks to this thread I was guided to the answer.
In my NewCampaignController I did:
#InitBinder
public void initBinder(WebDataBinder binder) {
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, dateEditor);
binder.registerCustomEditor(CampaignCities.class, "cities", new PropertyEditorSupport() {
#Override
public void setAsText(String text) {
String [] ids = text.split(",");
CampaignCities cities = null;
for(String id:ids){
if(cities == null)
cities = new CampaignCities();
City city = cityManager.getCity(new Long(id));
if(city != null)
cities.getCities().add(city);
}
if(cities != null){
cities.setId(null);
setValue(cities);
}
}
});