spring-data-jpa insert an entire entity - spring

I'm new to spring-data-jpa and I've been doing just fine with reading records out of a database but now I would like to insert records. I would like to follow my same pattern of using the repository class along with a query to do the insertion. Is there a way similar to this post https://stackoverflow.com/a/24848086/3299397 where I can insert a record but instead of explicitly specifying each value I simply pass to the function an entity object and insert the entire object? Here is what I have so far.
Entity Class:
package blah.blah.blah;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
#Entity
#Table(name = "MESSAGE")
public class Message implements Serializable {
#Id
// #GeneratedValue(generator = "system-uuid")
// #GenericGenerator(name = "system-uuid", strategy = "uuid")
#Column(name = "MESSAGE_GUID")
#GeneratedValue(generator = "uuid")
#GenericGenerator(name = "uuid", strategy = "uuid")
private String messageGuid;
#Column(name = "MESSAGE_TYPE_CD")
private Long messageTypeCd;
#Column(name = "SENDER_GUID")
private String SenderGuid;
#Column(name = "MESSAGE_TITLE")
private String messageTitle;
#Column(name = "MESSAGE_STATUS_CD")
private Long messageStatusCd;
#Column(name = "ACTIVATED_DT")
private Date activatedDt;
#Column(name = "DEACTIVATED_DT")
private Date deactivatedDt;
#Column(name = "CREATE_BY")
private String createBy;
#Column(name = "CREATE_DT")
private Date createDt;
#Column(name = "UPDATE_BY")
private String updateBy;
#Column(name = "UPDATE_DT")
private Date updateDt;
// required by JPA
public Message() {
}
#SuppressWarnings("all")
public Message(
String messageGuid,
Long messageTypeCd,
String SenderGuid,
String messageTitle,
Long messageStatusCd,
Date activatedDt,
Date deactivatedDt,
String createBy,
Date createDt,
String updateBy,
Date updateDt) {
super();
this.messageGuid = messageGuid;
this.messageTypeCd = messageTypeCd;
this.SenderGuid = SenderGuid;
this.messageTitle = messageTitle;
this.messageStatusCd = messageStatusCd;
this.activatedDt = activatedDt;
this.deactivatedDt = deactivatedDt;
this.createBy = createBy;
this.createDt = createDt;
this.updateBy = updateBy;
this.updateDt = updateDt;
}
public String getMessageGuid() {
return messageGuid;
}
public void setMessageGuid(String messageGuid) {
this.messageGuid = messageGuid;
}
public Long getMessageTypeCd() {
return messageTypeCd;
}
public void setMessageTypeCd(Long messageTypeCd) {
this.messageTypeCd = messageTypeCd;
}
public String getSenderGuid() {
return SenderGuid;
}
public void setSenderGuid(String senderGuid) {
SenderGuid = senderGuid;
}
public String getMessageTitle() {
return messageTitle;
}
public void setMessageTitle(String messageTitle) {
this.messageTitle = messageTitle;
}
public Long getMessageStatusCd() {
return messageStatusCd;
}
public void setMessageStatusCd(Long messageStatusCd) {
this.messageStatusCd = messageStatusCd;
}
public Date getActivatedDt() {
return activatedDt;
}
public void setActivatedDt(Date activatedDt) {
this.activatedDt = activatedDt;
}
public Date getDeactivatedDt() {
return deactivatedDt;
}
public void setDeactivatedDt(Date deactivatedDt) {
this.deactivatedDt = deactivatedDt;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getCreateDt() {
return createDt;
}
public void setCreateDt(Date createDt) {
this.createDt = createDt;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public Date getUpdateDt() {
return updateDt;
}
public void setUpdateDt(Date updateDt) {
this.updateDt = updateDt;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((SenderGuid == null) ? 0 : SenderGuid.hashCode());
result = prime * result + ((activatedDt == null) ? 0 : activatedDt.hashCode());
result = prime * result + ((createBy == null) ? 0 : createBy.hashCode());
result = prime * result + ((createDt == null) ? 0 : createDt.hashCode());
result = prime * result + ((deactivatedDt == null) ? 0 : deactivatedDt.hashCode());
result = prime * result + ((messageGuid == null) ? 0 : messageGuid.hashCode());
result = prime * result + ((messageStatusCd == null) ? 0 : messageStatusCd.hashCode());
result = prime * result + ((messageTitle == null) ? 0 : messageTitle.hashCode());
result = prime * result + ((messageTypeCd == null) ? 0 : messageTypeCd.hashCode());
result = prime * result + ((updateBy == null) ? 0 : updateBy.hashCode());
result = prime * result + ((updateDt == null) ? 0 : updateDt.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;
Message other = (Message) obj;
if (SenderGuid == null) {
if (other.SenderGuid != null)
return false;
} else if (!SenderGuid.equals(other.SenderGuid))
return false;
if (activatedDt == null) {
if (other.activatedDt != null)
return false;
} else if (!activatedDt.equals(other.activatedDt))
return false;
if (createBy == null) {
if (other.createBy != null)
return false;
} else if (!createBy.equals(other.createBy))
return false;
if (createDt == null) {
if (other.createDt != null)
return false;
} else if (!createDt.equals(other.createDt))
return false;
if (deactivatedDt == null) {
if (other.deactivatedDt != null)
return false;
} else if (!deactivatedDt.equals(other.deactivatedDt))
return false;
if (messageGuid == null) {
if (other.messageGuid != null)
return false;
} else if (!messageGuid.equals(other.messageGuid))
return false;
if (messageStatusCd == null) {
if (other.messageStatusCd != null)
return false;
} else if (!messageStatusCd.equals(other.messageStatusCd))
return false;
if (messageTitle == null) {
if (other.messageTitle != null)
return false;
} else if (!messageTitle.equals(other.messageTitle))
return false;
if (messageTypeCd == null) {
if (other.messageTypeCd != null)
return false;
} else if (!messageTypeCd.equals(other.messageTypeCd))
return false;
if (updateBy == null) {
if (other.updateBy != null)
return false;
} else if (!updateBy.equals(other.updateBy))
return false;
if (updateDt == null) {
if (other.updateDt != null)
return false;
} else if (!updateDt.equals(other.updateDt))
return false;
return true;
}
#Override
public String toString() {
return "Message [messageGuid=" + messageGuid + ", messageTypeCd=" + messageTypeCd + ", SenderGuid="
+ SenderGuid + ", messageTitle=" + messageTitle + ", messageStatusCd=" + messageStatusCd
+ ", activatedDt=" + activatedDt + ", deactivatedDt=" + deactivatedDt + ", createBy=" + createBy
+ ", createDt=" + createDt + ", updateBy=" + updateBy + ", updateDt=" + updateDt + "]";
}
}
Repository Class:
package blah.blah.blah;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
#Repository
public interface MessageRepository extends JpaRepository<Message, String> {
#Query("SELECT "
+ "m "
+ "FROM Message m "
+ "WHERE messageGuid = :messageGuid")
List<Message> findByMessageGuid(#Param("messageGuid") String messageGuid);
// THIS DOES NOT WORK!
// #Query("INSERT "
// + "INTO Message")
// void insertMessage(#Param("myMessage") Message myMessage);
}
Service Class:
package blah.blah.blah;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class MessageServiceImpl implements MessageService {
private static final Logger log = LoggerFactory.getLogger(MessageServiceImpl.class);
#Autowired
private MessageRepository messageRepository;
#Override
public void getMessage(String messageGuid) {
List<Message> messageList = messageRepository.findByMessageGuid(messageGuid);
for (Message message : messageList)
log.info("\n\n" + message.toString() + "\n\n");
}
Component Class:
#Component
public class MessageComponentThingy {
#Autowired
MessageService messageService;
public void thisIsALongExample() {
messageService.getMessage("34A02DCF520F0831E053870910ACED7A");
}
}
This works for me when I want to read a record from the database...
Update Note: Please note that I am not necessarily concerned with doing 'Native Queries' I would just like to keep the same general pattern as what is shown in my Repository class. I would not reject an answer that uses a Native Query though. It honestly doesn't matter to me.

I didn't realize how simple this was. I am already inheriting the JpaRepository inside my repository class. JpaRepository has a method called 'save'. So you simply call that method. Everything works now....
I added new code below to the Service class (there's a new put method for the insert) and to the Component class (you can see me call the service classes put method). Hope this helps someone in the future.
Entity Class:
package blah.blah.blah;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
#Entity
#Table(name = "MESSAGE")
public class Message implements Serializable {
#Id
// #GeneratedValue(generator = "system-uuid")
// #GenericGenerator(name = "system-uuid", strategy = "uuid")
#Column(name = "MESSAGE_GUID")
#GeneratedValue(generator = "uuid")
#GenericGenerator(name = "uuid", strategy = "uuid")
private String messageGuid;
#Column(name = "MESSAGE_TYPE_CD")
private Long messageTypeCd;
#Column(name = "SENDER_GUID")
private String SenderGuid;
#Column(name = "MESSAGE_TITLE")
private String messageTitle;
#Column(name = "MESSAGE_STATUS_CD")
private Long messageStatusCd;
#Column(name = "ACTIVATED_DT")
private Date activatedDt;
#Column(name = "DEACTIVATED_DT")
private Date deactivatedDt;
#Column(name = "CREATE_BY")
private String createBy;
#Column(name = "CREATE_DT")
private Date createDt;
#Column(name = "UPDATE_BY")
private String updateBy;
#Column(name = "UPDATE_DT")
private Date updateDt;
// required by JPA
public Message() {
}
#SuppressWarnings("all")
public Message(
String messageGuid,
Long messageTypeCd,
String SenderGuid,
String messageTitle,
Long messageStatusCd,
Date activatedDt,
Date deactivatedDt,
String createBy,
Date createDt,
String updateBy,
Date updateDt) {
super();
this.messageGuid = messageGuid;
this.messageTypeCd = messageTypeCd;
this.SenderGuid = SenderGuid;
this.messageTitle = messageTitle;
this.messageStatusCd = messageStatusCd;
this.activatedDt = activatedDt;
this.deactivatedDt = deactivatedDt;
this.createBy = createBy;
this.createDt = createDt;
this.updateBy = updateBy;
this.updateDt = updateDt;
}
public String getMessageGuid() {
return messageGuid;
}
public void setMessageGuid(String messageGuid) {
this.messageGuid = messageGuid;
}
public Long getMessageTypeCd() {
return messageTypeCd;
}
public void setMessageTypeCd(Long messageTypeCd) {
this.messageTypeCd = messageTypeCd;
}
public String getSenderGuid() {
return SenderGuid;
}
public void setSenderGuid(String senderGuid) {
SenderGuid = senderGuid;
}
public String getMessageTitle() {
return messageTitle;
}
public void setMessageTitle(String messageTitle) {
this.messageTitle = messageTitle;
}
public Long getMessageStatusCd() {
return messageStatusCd;
}
public void setMessageStatusCd(Long messageStatusCd) {
this.messageStatusCd = messageStatusCd;
}
public Date getActivatedDt() {
return activatedDt;
}
public void setActivatedDt(Date activatedDt) {
this.activatedDt = activatedDt;
}
public Date getDeactivatedDt() {
return deactivatedDt;
}
public void setDeactivatedDt(Date deactivatedDt) {
this.deactivatedDt = deactivatedDt;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getCreateDt() {
return createDt;
}
public void setCreateDt(Date createDt) {
this.createDt = createDt;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public Date getUpdateDt() {
return updateDt;
}
public void setUpdateDt(Date updateDt) {
this.updateDt = updateDt;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((SenderGuid == null) ? 0 : SenderGuid.hashCode());
result = prime * result + ((activatedDt == null) ? 0 : activatedDt.hashCode());
result = prime * result + ((createBy == null) ? 0 : createBy.hashCode());
result = prime * result + ((createDt == null) ? 0 : createDt.hashCode());
result = prime * result + ((deactivatedDt == null) ? 0 : deactivatedDt.hashCode());
result = prime * result + ((messageGuid == null) ? 0 : messageGuid.hashCode());
result = prime * result + ((messageStatusCd == null) ? 0 : messageStatusCd.hashCode());
result = prime * result + ((messageTitle == null) ? 0 : messageTitle.hashCode());
result = prime * result + ((messageTypeCd == null) ? 0 : messageTypeCd.hashCode());
result = prime * result + ((updateBy == null) ? 0 : updateBy.hashCode());
result = prime * result + ((updateDt == null) ? 0 : updateDt.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;
Message other = (Message) obj;
if (SenderGuid == null) {
if (other.SenderGuid != null)
return false;
} else if (!SenderGuid.equals(other.SenderGuid))
return false;
if (activatedDt == null) {
if (other.activatedDt != null)
return false;
} else if (!activatedDt.equals(other.activatedDt))
return false;
if (createBy == null) {
if (other.createBy != null)
return false;
} else if (!createBy.equals(other.createBy))
return false;
if (createDt == null) {
if (other.createDt != null)
return false;
} else if (!createDt.equals(other.createDt))
return false;
if (deactivatedDt == null) {
if (other.deactivatedDt != null)
return false;
} else if (!deactivatedDt.equals(other.deactivatedDt))
return false;
if (messageGuid == null) {
if (other.messageGuid != null)
return false;
} else if (!messageGuid.equals(other.messageGuid))
return false;
if (messageStatusCd == null) {
if (other.messageStatusCd != null)
return false;
} else if (!messageStatusCd.equals(other.messageStatusCd))
return false;
if (messageTitle == null) {
if (other.messageTitle != null)
return false;
} else if (!messageTitle.equals(other.messageTitle))
return false;
if (messageTypeCd == null) {
if (other.messageTypeCd != null)
return false;
} else if (!messageTypeCd.equals(other.messageTypeCd))
return false;
if (updateBy == null) {
if (other.updateBy != null)
return false;
} else if (!updateBy.equals(other.updateBy))
return false;
if (updateDt == null) {
if (other.updateDt != null)
return false;
} else if (!updateDt.equals(other.updateDt))
return false;
return true;
}
#Override
public String toString() {
return "Message [messageGuid=" + messageGuid + ", messageTypeCd=" + messageTypeCd + ", SenderGuid="
+ SenderGuid + ", messageTitle=" + messageTitle + ", messageStatusCd=" + messageStatusCd
+ ", activatedDt=" + activatedDt + ", deactivatedDt=" + deactivatedDt + ", createBy=" + createBy
+ ", createDt=" + createDt + ", updateBy=" + updateBy + ", updateDt=" + updateDt + "]";
}
}
Repository Class:
package blah.blah.blah;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
#Repository
public interface MessageRepository extends JpaRepository<Message, String> {
#Query("SELECT "
+ "m "
+ "FROM Message m "
+ "WHERE messageGuid = :messageGuid")
List<Message> findByMessageGuid(#Param("messageGuid") String messageGuid);
}
Service Class:
package blah.blah.blah;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class MessageServiceImpl implements MessageService {
private static final Logger log = LoggerFactory.getLogger(MessageServiceImpl.class);
#Autowired
private MessageRepository messageRepository;
#Override
public void getMessage(String messageGuid) {
List<Message> messageList = messageRepository.findByMessageGuid(messageGuid);
for (Message message : messageList)
log.info("\n\n" + message.toString() + "\n\n");
}
public void putMessage(Message message) {
messageRepository.save(message);
System.out.println("\n\nInside putMessage\n\n");
}
}
Component Class:
#Component
public class MessageComponentThingy {
#Autowired
MessageService messageService;
public void thisIsALongExample() {
messageService.getMessage("34A02DCF520F0831E053870910ACED7A");
Message message = new Message();
message.setMessageTypeCd(1L);
message.setSenderGuid("test");
message.setMessageTitle("test title");
message.setMessageStatusCd(1L);
message.setActivatedDt(new Date());
message.setDeactivatedDt(new Date());
message.setCreateBy("me");
message.setCreateDt(new Date());
message.setUpdateBy("me");
message.setUpdateDt(new Date());
messageService.putMessage(message);
}
}

Related

hibernate adding Id column field while building query

Hibernate not creating correct query, In API request I have passed sort=employee.firstName that should return records sort by firstName but hibernate some how adding extra field case_id after firstName. I have debug the code and in sort only one field is there which is employee.firstName, so my question is how hibernate is adding case_id to the query.
Below is my API URL.
/api/v1/cases?sort=employee.firstName,ASC&size=50&page=0&statusCategories=open,in_progress&filter=caseType:customer_care
I have not passes sort by case_id instead sort by firstName is passed.
Hibernate Query below:
SELECT
case0_.case_id AS case_id1_8_,
case0_.archived_from AS archived_from2_8_,
case0_.assignee_id AS assignee_id3_8_,
case0_.status_id AS status_id15_8_,
case0_.type AS type4_8_,
case0_.category_id AS category_id5_8_,
case0_.employeegroup_id AS employeegroup_id11_8_,
case0_.created_by AS created_by6_8_,
case0_.created_date AS created_date7_8_,
case0_.customer_id AS customer_id8_8_,
case0_.description AS description9_8_,
case0_.due_date AS due_date10_8_,
case0_.eventmanager_id AS eventmanager_id12_8_,
case0_.resolution_date AS resolution_date13_8_,
case0_.resort_id AS resort_id14_8_,
case0_.topic AS topic16_8_
FROM
CASE case0_
LEFT OUTER JOIN employee client1_ ON
case0_.created_by = client1_.employee_id
WHERE
(case0_.status_id IN (
SELECT
casestatus2_.case_status_id
FROM
case_status casestatus2_
WHERE
casestatus2_.category IN (? , ?)))
AND (case0_.archived_from IS NULL)
AND case0_.type =?
ORDER BY
client1_.firstname ASC,
case0_.case_id ASC offset ? ROWS FETCH NEXT ? ROWS ONLY
[Screenshot in debug mode, as u can see the sort variable only having one field][1]
[1]: https://i.stack.imgur.com/7DRYJ.png
Controller Code:
#RequestMapping(method = RequestMethod.GET)
public Page<Case> getCases(#FilterOptions(joinedEntities = { #JoinedEntity(fieldName = "client", filterName = "client"), #JoinedEntity(fieldName = "clientGroup", filterName = "clientGroup"),
#JoinedEntity(fieldName = "caseStatus", filterName = "caseStatus"), #JoinedEntity(fieldName = "memoCategory", filterName = "memoCategory"),
#JoinedEntity(fieldName = "employee", filterName = "employee") }) Specification<Case> specifications, Pageable pageable, CaseFilter caseFilter) {
return caseService.getCases(specifications, pageable, caseFilter);
}
Domain Class:
#Entity
#Table(name = "case")
#DynamicJsonView
#DynamicUpdate
public class Case implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_CASE")
#SequenceGenerator(name = "SEQ_CASE", sequenceName = "SEQ_CASE", allocationSize = 1)
#Column(name = "case_id")
private Long caseId;
#Column(name = "topic")
#NotNull
private String topic;
#Column(name = "description")
private String description;
#Column(name = "status_id")
private Long statusId;
#Column(name = "assignee_id")
private Long assigneeId;
#Column(name = "customer_id")
private Long customerId;
#Column(name = "created_date")
private LocalDateTime creationDate;
#Column(name = "due_date")
private LocalDate dueDate;
#Column(name = "resolution_date")
private LocalDate resolutionDate;
#Column(name = "category_id")
private Long categoryId;
#Column(name = "archived_from")
private LocalDate archivedFrom;
#OneToOne
#JoinColumn(name = "assignee_id", referencedColumnName = "employee_id", updatable = false, insertable = false)
#JsonIgnore
private Client client;
#OneToOne
#JoinColumn(name = "employeegroup_id", referencedColumnName = "employeegroup_id", insertable = false, updatable = false)
#JsonIgnore
private ClientGroup clientGroup;
#OneToOne
#JsonIgnore
#JoinColumn(name = "status_id", referencedColumnName = "case_status_id", insertable = false, updatable = false)
private CaseStatus caseStatus;
#OneToOne
#JsonIgnore
#JoinColumn(name = "category_id", referencedColumnName = "memocategory_id", insertable = false, updatable = false)
private MemoCategory memoCategory;
#Column(name = "employeegroup_id")
private Long employeeGroupId;
#Column(name = "created_by")
private Long createdBy;
#Column(name = "resort_id")
private Long resortId;
#Column(name = "type")
private CaseType caseType;
#Column(name = "eventmanager_id")
private Long eventManagerId;
#OneToOne
#JoinColumn(name = "created_by", referencedColumnName = "employee_id", updatable = false, insertable = false)
#JsonIgnore
private Client employee;
public Long getEventManagerId() {
return eventManagerId;
}
public void setEventManagerId(Long eventManagerId) {
this.eventManagerId = eventManagerId;
}
public CaseType getCaseType() {
return caseType;
}
public void setCaseType(CaseType caseType) {
this.caseType = caseType;
}
public Long getResortId() {
return resortId;
}
public void setResortId(Long resortId) {
this.resortId = resortId;
}
public Long getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Long createdBy) {
this.createdBy = createdBy;
}
public Long getEmployeeGroupId() {
return employeeGroupId;
}
public void setEmployeeGroupId(Long employeeGroupId) {
this.employeeGroupId = employeeGroupId;
}
public LocalDate getArchivedFrom() {
return archivedFrom;
}
public void setArchivedFrom(LocalDate archivedFrom) {
this.archivedFrom = archivedFrom;
}
public Long getCaseId() {
return caseId;
}
public void setCaseId(Long caseId) {
this.caseId = caseId;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getStatusId() {
return statusId;
}
public void setStatusId(Long statusId) {
this.statusId = statusId;
}
public Long getAssigneeId() {
return assigneeId;
}
public void setAssigneeId(Long assigneeId) {
this.assigneeId = assigneeId;
}
public Long getCustomerId() {
return customerId;
}
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
public LocalDateTime getCreationDate() {
return creationDate;
}
public void setCreationDate(LocalDateTime creationDate) {
this.creationDate = creationDate;
}
public LocalDate getDueDate() {
return dueDate;
}
public void setDueDate(LocalDate dueDate) {
this.dueDate = dueDate;
}
public LocalDate getResolutionDate() {
return resolutionDate;
}
public void setResolutionDate(LocalDate resolutionDate) {
this.resolutionDate = resolutionDate;
}
public Long getCategoryId() {
return categoryId;
}
public void setCategoryId(Long categoryId) {
this.categoryId = categoryId;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((archivedFrom == null) ? 0 : archivedFrom.hashCode());
result = prime * result + ((assigneeId == null) ? 0 : assigneeId.hashCode());
result = prime * result + ((caseId == null) ? 0 : caseId.hashCode());
result = prime * result + ((caseStatus == null) ? 0 : caseStatus.hashCode());
result = prime * result + ((caseType == null) ? 0 : caseType.hashCode());
result = prime * result + ((categoryId == null) ? 0 : categoryId.hashCode());
result = prime * result + ((client == null) ? 0 : client.hashCode());
result = prime * result + ((clientGroup == null) ? 0 : clientGroup.hashCode());
result = prime * result + ((createdBy == null) ? 0 : createdBy.hashCode());
result = prime * result + ((creationDate == null) ? 0 : creationDate.hashCode());
result = prime * result + ((customerId == null) ? 0 : customerId.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((dueDate == null) ? 0 : dueDate.hashCode());
result = prime * result + ((employee == null) ? 0 : employee.hashCode());
result = prime * result + ((employeeGroupId == null) ? 0 : employeeGroupId.hashCode());
result = prime * result + ((eventManagerId == null) ? 0 : eventManagerId.hashCode());
result = prime * result + ((memoCategory == null) ? 0 : memoCategory.hashCode());
result = prime * result + ((resolutionDate == null) ? 0 : resolutionDate.hashCode());
result = prime * result + ((resortId == null) ? 0 : resortId.hashCode());
result = prime * result + ((statusId == null) ? 0 : statusId.hashCode());
result = prime * result + ((topic == null) ? 0 : topic.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;
}
Case other = (Case) obj;
if (archivedFrom == null) {
if (other.archivedFrom != null) {
return false;
}
}
else if (!archivedFrom.equals(other.archivedFrom)) {
return false;
}
if (assigneeId == null) {
if (other.assigneeId != null) {
return false;
}
}
else if (!assigneeId.equals(other.assigneeId)) {
return false;
}
if (caseId == null) {
if (other.caseId != null) {
return false;
}
}
else if (!caseId.equals(other.caseId)) {
return false;
}
if (caseStatus == null) {
if (other.caseStatus != null) {
return false;
}
}
else if (!caseStatus.equals(other.caseStatus)) {
return false;
}
if (caseType != other.caseType) {
return false;
}
if (categoryId == null) {
if (other.categoryId != null) {
return false;
}
}
else if (!categoryId.equals(other.categoryId)) {
return false;
}
if (client == null) {
if (other.client != null) {
return false;
}
}
else if (!client.equals(other.client)) {
return false;
}
if (clientGroup == null) {
if (other.clientGroup != null) {
return false;
}
}
else if (!clientGroup.equals(other.clientGroup)) {
return false;
}
if (createdBy == null) {
if (other.createdBy != null) {
return false;
}
}
else if (!createdBy.equals(other.createdBy)) {
return false;
}
if (creationDate == null) {
if (other.creationDate != null) {
return false;
}
}
else if (!creationDate.equals(other.creationDate)) {
return false;
}
if (customerId == null) {
if (other.customerId != null) {
return false;
}
}
else if (!customerId.equals(other.customerId)) {
return false;
}
if (description == null) {
if (other.description != null) {
return false;
}
}
else if (!description.equals(other.description)) {
return false;
}
if (dueDate == null) {
if (other.dueDate != null) {
return false;
}
}
else if (!dueDate.equals(other.dueDate)) {
return false;
}
if (employee == null) {
if (other.employee != null) {
return false;
}
}
else if (!employee.equals(other.employee)) {
return false;
}
if (employeeGroupId == null) {
if (other.employeeGroupId != null) {
return false;
}
}
else if (!employeeGroupId.equals(other.employeeGroupId)) {
return false;
}
if (eventManagerId == null) {
if (other.eventManagerId != null) {
return false;
}
}
else if (!eventManagerId.equals(other.eventManagerId)) {
return false;
}
if (memoCategory == null) {
if (other.memoCategory != null) {
return false;
}
}
else if (!memoCategory.equals(other.memoCategory)) {
return false;
}
if (resolutionDate == null) {
if (other.resolutionDate != null) {
return false;
}
}
else if (!resolutionDate.equals(other.resolutionDate)) {
return false;
}
if (resortId == null) {
if (other.resortId != null) {
return false;
}
}
else if (!resortId.equals(other.resortId)) {
return false;
}
if (statusId == null) {
if (other.statusId != null) {
return false;
}
}
else if (!statusId.equals(other.statusId)) {
return false;
}
if (topic == null) {
if (other.topic != null) {
return false;
}
}
else if (!topic.equals(other.topic)) {
return false;
}
return true;
}
Repositery Code:
#Repository
public interface CaseRepository extends MaxxtonJpaRepository<Case, Long> {
#Query(nativeQuery = true, value = "SELECT assignee_id FROM case WHERE assignee_id IN (SELECT employee_id FROM employee WHERE group_Id= :employeeGroupId ) group by assignee_id")
public List<Long> fetchEmployees(#Param(value = "employeeGroupId") Long employeeGroupId);
}
Another Repositery class:
#NoRepositoryBean
public interface MaxxtonJpaRepository<ENTITY, ID extends Serializable> extends FieldFilterRepository<ENTITY, ID>, JpaSpecificationExecutor<ENTITY> {
<P> List<P> findAll(Specification<ENTITY> spec, Class<P> projection);
<P> Page<P> findAll(Specification<ENTITY> specification, Class<P> projection, Pageable pageable);
ENTITY saveAndRefresh(ENTITY entity);
Iterable<ENTITY> saveAllAndRefresh(Iterable<ENTITY> entities);
}
How this case_id gets added in order by.

Returning incorrect values using JPA

I am relatively new to this. So I will try to be complete and concise. Using Eclipse and JPA, I am trying to establish a many to many relationship between drinks and liquors. I seem to be saving objects to the database, but am unable to retrieve the correct objects. Everything I have been able to find seems to indicate I have a correct format. So I am not certain why I am getting this result when I run the test
java.lang.AssertionError:
Expected: iterable over [, ] in any order
but: No item matches: , in []
This is my relevant test. I have been able to save to and load from the database from other tests.
package com.example.mixeddrinkapp;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.Assert.assertThat;
import java.util.Optional;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
#RunWith(SpringJUnit4ClassRunner.class)
#DataJpaTest
public class JPAMappingTest {
#Resource
private TestEntityManager entityManager;
#Resource
private DrinkRepository drinkRepo;
#Resource
private LiquorRepository liquorRepo;
#Test
public void shouldEstablishDrinktoLiquorRelationship() {
Liquor liquor = liquorRepo.save(new Liquor("liquor", true));
Liquor anotherLiquor = liquorRepo.save(new Liquor("anotherLiquor", true));
Drink drink = new Drink("name", liquor.getId(), anotherLiquor.getId(), null, null, null, null, null, null, null);
drink = drinkRepo.save(drink);
Long drinkId = drink.getId();
entityManager.flush();
entityManager.clear();
Optional<Drink> result = drinkRepo.findById(drinkId);
drink = result.get();
assertThat(drink.getLiquors(), containsInAnyOrder(liquor, anotherLiquor));
}
This is my Drink Class
package com.example.mixeddrinkapp;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
#Entity
public class Drink {
#Id
#GeneratedValue
private Long drinkId;
private String drinkName;
private Long liquor1;
private Long liquor2;
private Long liquor3;
private Long mixer1;
private Long mixer2;
private Long mixer3;
private Long garnish1;
private Long garnish2;
private Long garnish3;
#ManyToMany
private Collection<Liquor> liquors;
public Collection<Liquor> getLiquors() {
return liquors;
}
public void setLiquors(Collection<Liquor> liquors) {
this.liquors = liquors;
}
// default constructor
public Drink() {
}
public Drink(String drinkName, Long liquor1, Long liquor2, Long liquor3, Long mixer1, Long mixer2, Long mixer3,
Long garnish1, Long garnish2, Long garnish3) {
this.drinkName = drinkName;
this.liquor1 = liquor1;
this.liquor2 = liquor2;
this.liquor3 = liquor3;
this.mixer1 = mixer1;
this.mixer2 = mixer2;
this.mixer3 = mixer3;
this.garnish1 = garnish1;
this.garnish2 = garnish2;
this.garnish3 = garnish3;
}
public long getId() {
return drinkId;
}
public String getName() {
return drinkName;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (drinkId ^ (drinkId >>> 32));
result = prime * result + ((drinkName == null) ? 0 : drinkName.hashCode());
result = prime * result + (int) (garnish1 ^ (garnish1 >>> 32));
result = prime * result + (int) (garnish2 ^ (garnish2 >>> 32));
result = prime * result + (int) (garnish3 ^ (garnish3 >>> 32));
result = prime * result + (int) (liquor1 ^ (liquor1 >>> 32));
result = prime * result + (int) (liquor2 ^ (liquor2 >>> 32));
result = prime * result + (int) (liquor3 ^ (liquor3 >>> 32));
result = prime * result + ((liquors == null) ? 0 : liquors.hashCode());
result = prime * result + (int) (mixer1 ^ (mixer1 >>> 32));
result = prime * result + (int) (mixer2 ^ (mixer2 >>> 32));
result = prime * result + (int) (mixer3 ^ (mixer3 >>> 32));
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Drink other = (Drink) obj;
if (drinkId != other.drinkId)
return false;
if (drinkName == null) {
if (other.drinkName != null)
return false;
} else if (!drinkName.equals(other.drinkName))
return false;
if (garnish1 != other.garnish1)
return false;
if (garnish2 != other.garnish2)
return false;
if (garnish3 != other.garnish3)
return false;
if (liquor1 != other.liquor1)
return false;
if (liquor2 != other.liquor2)
return false;
if (liquor3 != other.liquor3)
return false;
if (liquors == null) {
if (other.liquors != null)
return false;
} else if (!liquors.equals(other.liquors))
return false;
if (mixer1 != other.mixer1)
return false;
if (mixer2 != other.mixer2)
return false;
if (mixer3 != other.mixer3)
return false;
return true;
}
This is my Liquor class.
package com.example.mixeddrinkapp;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
#Entity
public class Liquor {
#Id
#GeneratedValue
private Long liquorId;
private String name;
private boolean inStock;
#ManyToMany(mappedBy = "liquors")
private Collection<Drink> drinks;
public Collection<Drink> getDrinks() {
return drinks;
}
public void setDrinks(Collection<Drink> drinks) {
this.drinks = drinks;
}
// default constructor
public Liquor() {
}
public Liquor(String name, boolean inStock) {
this.name = name;
this.inStock = inStock;
}
public String getName() {
return name;
}
public boolean getInStock() {
return inStock;
}
public Long getId() {
return liquorId;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((drinks == null) ? 0 : drinks.hashCode());
result = prime * result + (inStock ? 1231 : 1237);
result = prime * result + ((liquorId == null) ? 0 : liquorId.hashCode());
result = prime * result + ((name == null) ? 0 : name.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;
Liquor other = (Liquor) obj;
if (drinks == null) {
if (other.drinks != null)
return false;
} else if (!drinks.equals(other.drinks))
return false;
if (inStock != other.inStock)
return false;
if (liquorId == null) {
if (other.liquorId != null)
return false;
} else if (!liquorId.equals(other.liquorId))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}

Issue in Saving entities with Many to Many relation in SpringData JPA / Hibernate

I have Many-to-many relation for user to role entity.
So I created Bidirectional mapping with link entity life cycle.
Note: Role table is already prepopulated with the data by other process
Employee.java
#Entity
#Table(name="EMPLOYEE")
public class Employee {
#Id
#GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "EMPLOYEE_SEQ"
)
#GenericGenerator(
name = "EMPLOYEE_SEQ",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
#Parameter(name = "sequence_name", value = "EMPLOYEE_SEQ"),
#Parameter(name = "initial_value", value = "1"),
#Parameter(name = "increment_size", value = "3"),
#Parameter(name = "optimizer", value = "pooled-lo")
}
)
private Long id;
#Column(name="NAME")
private String name;
#OneToMany(mappedBy="employee", cascade= CascadeType.ALL,orphanRemoval=true)
private List<EmployeeRole> roles = new ArrayList<EmployeeRole>();
// Removed setters and getters
#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;
Employee other = (Employee) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
public void addRole(Role role)
{
EmployeeRole employeeRole = new EmployeeRole(this,role);
roles.add(employeeRole);
role.getEmployee().add(employeeRole);
}
}
Role.Java
#Entity
#Table(name="ROLE")
public class Role {
#Id
private Long id;
private String roleName;
#OneToMany(mappedBy="role",cascade = CascadeType.ALL,orphanRemoval= true)
private List<EmployeeRole> employee = new ArrayList<EmployeeRole>();
#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;
Role other = (Role) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
EmployeeRole.java
#Entity(name = "EmployeeRole")
public class EmployeeRole implements Serializable {
public EmployeeRole() {
}
public EmployeeRole(Employee employee, Role role) {
super();
this.employee = employee;
this.role = role;
}
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#ManyToOne
private Employee employee;
#Id
#ManyToOne
private Role role;
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((employee == null) ? 0 : employee.hashCode());
result = prime * result + ((role == null) ? 0 : role.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;
EmployeeRole other = (EmployeeRole) obj;
if (employee == null) {
if (other.employee != null)
return false;
} else if (!employee.equals(other.employee))
return false;
if (role == null) {
if (other.role != null)
return false;
} else if (!role.equals(other.role))
return false;
return true;
}
}
EmployeeService.java
#Autowired
EmployeeRepository employeeRepo;
#Autowired
RoleRepository roleRepo;
#Transactional
public void addEmployee(EmployeeDTO employeedto) {
Employee employeeDB = employeeRepo.findByName(employeedto.getEmployeeName());
Role roleDB = roleRepo.findByRoleName(employeedto.getRoles().get(0).getRoleName());
if(employeeDB==null) {
employeeDB = new Employee();
}
employeeDB.setName(employeedto.getEmployeeName());
if(roleDB == null) {
roleDB = new Role();
}
employeeDB.addRole(roleDB);
employeeRepo.save(employeeDB);
}
Problem Statement:
When I save the below Request body, I was able to create the new employee Sara and link the 'Admin' role.
{
"employeeName": "Sara",
"roles": [{
"roleName": "Admin"
}
]
}
But when I try to link another role 'Read' to the same user 'Sara' I am getting the below exception
{
"employeeName": "Sara",
"roles": [{
"roleName": "Read"
}
]
}
Exception:
2019-12-12 14:01:21.625 WARN 41064 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1400, SQLState: 23000
2019-12-12 14:01:21.625 ERROR 41064 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : ORA-01400: cannot insert NULL into ("SCHEMA"."EMPLOYEE_ROLE"."ROLE_ID")
Thoughts on this please.

Spring - NoSuchMethodException when calling a RestService

I have this simple Mapping that should return me a List objects
#RestController
#RequestMapping(value="/api")
public class ServerRESTController {
#Autowired ServerService serverService;
#RequestMapping(value="/server/{idServer}", method = RequestMethod.GET)
public ResponseEntity<Server> getFloorLatUpdate(#PathVariable int idServer){
Server server = serverService.findById(idServer);
return new ResponseEntity<Server>(server, HttpStatus.OK);
}
#RequestMapping(value="/server/list", method = RequestMethod.GET)
public ResponseEntity<List<Server>> listAllServers(){
List<Server> servers = serverService.findAllServers(-1);
return new ResponseEntity<List<Server>>(servers, HttpStatus.OK);
}
}
Server.class is a model
#Entity
#Table(name = "server")
public class Server implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private int serverId;
private Piano piano;
private String nomeServer;
private String serverIp;
private String descrizione;
private boolean online;
private Set<Interruttore> interruttori;
private String firmwareVersion;
public Server(){
}
public Server(int serverId, Piano piano, String nomeServer, String serverIp, String descrizione, boolean online,
Set<Interruttore> interruttori, String firmwareVersion){
this.serverId = serverId;
this.piano = piano;
this.nomeServer = nomeServer;
this.descrizione = descrizione;
this.serverIp = serverIp;
this.online = online;
this.interruttori = interruttori;
this.setFirmwareVersion(firmwareVersion);
}
#Id
#Column(name = "id_server", unique = true, nullable = false)
#GeneratedValue(strategy = IDENTITY)
public int getServerId() {
return serverId;
}
public void setServerId(int serverId) {
this.serverId = serverId;
}
#ManyToOne
#JoinColumn(name="id_piano")
public Piano getPiano() {
return piano;
}
public void setPiano(Piano piano) {
this.piano = piano;
}
#Column(name="nome_server")
public String getNomeServer() {
return nomeServer;
}
public void setNomeServer(String nomeServer) {
this.nomeServer = nomeServer;
}
#Column(name="server_ip")
public String getServerIp() {
return serverIp;
}
public void setServerIp(String serverIp) {
this.serverIp = serverIp;
}
#Column(name="descrizione")
public String getDescrizione() {
return descrizione;
}
public void setDescrizione(String descrizione) {
this.descrizione = descrizione;
}
#Column(name="online")
public boolean isOnline() {
return online;
}
public void setOnline(boolean online) {
this.online = online;
}
#JsonIgnore
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "server")
public Set<Interruttore> getInterruttori() {
return interruttori;
}
public void setInterruttori(Set<Interruttore> interruttori) {
this.interruttori = interruttori;
}
#Column(name = "firmware_version")
public String getFirmwareVersion() {
return firmwareVersion;
}
public void setFirmwareVersion(String firmwareVersion) {
this.firmwareVersion = firmwareVersion;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((descrizione == null) ? 0 : descrizione.hashCode());
result = prime * result + ((nomeServer == null) ? 0 : nomeServer.hashCode());
result = prime * result + (online ? 1231 : 1237);
result = prime * result + ((piano == null) ? 0 : piano.hashCode());
result = prime * result + serverId;
result = prime * result + ((serverIp == null) ? 0 : serverIp.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;
Server other = (Server) obj;
if (descrizione == null) {
if (other.descrizione != null)
return false;
} else if (!descrizione.equals(other.descrizione))
return false;
if (nomeServer == null) {
if (other.nomeServer != null)
return false;
} else if (!nomeServer.equals(other.nomeServer))
return false;
if (online != other.online)
return false;
if (piano == null) {
if (other.piano != null)
return false;
} else if (!piano.equals(other.piano))
return false;
if (serverId != other.serverId)
return false;
if (serverIp == null) {
if (other.serverIp != null)
return false;
} else if (!serverIp.equals(other.serverIp))
return false;
return true;
}
}
When trying to call for the service i'm getting:
HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalStateException: Method [listAllServers] was discovered in the .class file but cannot be resolved in the class object
cause by
java.lang.NoSuchMethodException: it.besmart.restcontroller.ServerRESTController.listAllServers()
I cannot understand why this happens, I have always used ResponseEntity in this way... maybe it's for the List?
Please post the whole code so we can find out.
This usually comes when the method is invoked at the wrong place or when there is a mismatch in build and runtime environments or when you miss arguments in a constructor and so on.
Also, you may want to check the files in the classpath. There may be a mismatch between compile time and actual runtime environments for some reason. For example, you say that you build it using command line. So, there may be some discrepancy there, no harm in checking.
Finally, you can check for spelling mistakes - I know that sounds strange, but case sensitivity is important.

AsyncTask Crashing on postExecute

I have a problem when using asyntask to query all the data in a table and put it in an array List and then send it to the server. I am able to send the data to the server successfully. But the application crashes on the postexecute of the asynctask giving the following error:
(W/System.errīš• org.json.JSONException: Value ["com.atlantis.eclectics.agentbank.SyncMembersActivity$MemberRecords#41b06d18","com.atlantis.eclectics.agentbank.SyncMembersActivity$MemberRecords#41b070b8"] of type org.json.JSONArray cannot be converted to JSONObject)..
What could be problem? Where am i getting it wrong. Someone please help...Thanks very much.
package com.practical.tasks.school;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
#SuppressWarnings("deprecation")
public class SyncMembersActivity extends ActionBarActivity {
CustomHttpClient jParser = new CustomHttpClient();
ListView lstView;
public MainDB dbs;
public SQLiteDatabase db;
public static String fname;
String username = "atlantis";
String password = "#t1#ntis";
Button submit;
String statusN = "NO";
String statusY = "YES";
String url = "http://123.456.78.90:1234/Api/create/Post";
String FirstName = "";
String SecondName = "";
String MobileNumber = "";
String DateofBirth = "";
String Gender = "";
String GroupName = "";
String GroupAccountNo = "";
String IdentificationID = "";
String IdentificationType = null;
String CreatedBy = null;
String Residence = "";
private int notificationIdOne = 111;
private int numMessagesOne = 0;
private NotificationManager myNotificationManager;
String account_statusY = "True";
private ProgressDialog prgDialog;
private ArrayAdapter<String> listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sync_members);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeActionContentDescription("Services");
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#5A92F7")));
lstView = (ListView) findViewById(R.id.lstSample);
submit = (Button) findViewById(R.id.upload);
prgDialog = new ProgressDialog(this);
prgDialog.setMessage("Please wait...");
prgDialog.setCancelable(false);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (isNetworkAvailable(getApplicationContext())) {
new HttpAsyncTask().execute(FirstName, SecondName, MobileNumber, DateofBirth, Gender, GroupName, GroupAccountNo, IdentificationID, IdentificationType, CreatedBy, Residence);
} else {
showAlert("No internet Connectivity...");
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_sync_members, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class MemberRecords {
String FirstName;
String SecondName;
String MobileNumber;
String DateofBirth;
String Gender;
String GroupName;
String GroupAccountNo;
String IdentificationID;
String IdentificationType;
String CreatedBy;
String Residence;
public String getFirstName() {
return FirstName;
}
public String getSecondName() {
return SecondName;
}
public String getMobileNumber() {
return MobileNumber;
}
public String getDateofBirth() {
return DateofBirth;
}
public String getGender() {
return Gender;
}
public String getGroupName() {
return GroupName;
}
public String getGroupAccountNo() {
return GroupAccountNo;
}
public String getIdentificationID() {
return IdentificationID;
}
public String getIdentificationType() {
return IdentificationType;
}
public String getCreatedBy() {
return CreatedBy;
}
public String getResidence() {
return Residence;
}
public void setFirstName(String newfirstName) {
FirstName = newfirstName;
}
public void setSecondName(String newSecondName) {
SecondName = newSecondName;
}
public void setMobileNumber(String mobileNumber) {
MobileNumber = mobileNumber;
}
public void setDateofBirth(String dateofBirth) {
DateofBirth = dateofBirth;
}
public void setGender(String gender) {
Gender = gender;
}
public void setGroupName(String groupName) {
GroupName = groupName;
}
public void setGroupAccountNo(String groupAccountNo) {
GroupAccountNo = groupAccountNo;
}
public void setIdentificationID(String identificationID) {
IdentificationID = identificationID;
}
public void setIdentificationType(String identificationType) {
IdentificationType = identificationType;
}
public void setCreatedBy(String createdBy) {
CreatedBy = createdBy;
}
public void setResidence(String residence) {
Residence = residence;
}
}
public boolean isConnected() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
public static String POST(String url, MemberRecords my) {
InputStream inputStream;
String result = "";
String username = "atlantis";
String password = "#t1#ntis";
Integer n;
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost("http://41.186.47.26:4433/Api/Account/PostAddSignatory");
String json = "";
Log.e("Url", "Url Here:" + url);
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("FirstName", my.getFirstName());
jsonObject.accumulate("SecondName", my.getSecondName());
jsonObject.accumulate("MobileNumber", my.getMobileNumber());
jsonObject.accumulate("DateofBirth", my.getDateofBirth());
jsonObject.accumulate("Gender", my.getGender());
jsonObject.accumulate("GroupName", my.getGroupName());
jsonObject.accumulate("GroupAccountNo", my.getGroupAccountNo());
jsonObject.accumulate("IdentificationID", my.getIdentificationID());
jsonObject.accumulate("IdentificationType", my.getIdentificationType());
jsonObject.accumulate("CreatedBy", my.getCreatedBy());
jsonObject.accumulate("Residence", my.getResidence());
json = jsonObject.toString();
Log.e("Url", "Request:" + json);
StringEntity se = new StringEntity(json);
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
Header header = new BasicScheme().authenticate(credentials, httpPost);
httpPost.addHeader(header);
httpPost.setEntity(se);
HttpResponse httpResponse = httpclient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.e("InputStream", e.getLocalizedMessage());
//e.printStackTrace();
}
// 11. return result
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException, JSONException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
Log.e("Url", "Response:" + result);
inputStream.close();
return result;
}
private class HttpAsyncTask extends AsyncTask<String, Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
prgDialog.show();
}
#Override
protected String doInBackground(String... urls) {
dbs = new MainDB(SyncMembersActivity.this);
db = dbs.getWritableDatabase();
Integer n=null;
MemberRecords my = new MemberRecords();
List<MemberRecords> member_list = new ArrayList<>();
try {
Cursor cursor = db.rawQuery("SELECT * FROM tbl_memberData" +
" where sync_status = '" + statusN + "' AND account_status = '" + account_statusY + "'", null);
if (cursor.moveToFirst()) {
do {
my = new MemberRecords();
my.setGroupName(cursor.getString(1));
my.setIdentificationID(cursor.getString(2));
my.setIdentificationType(cursor.getString(3));
my.setFirstName(cursor.getString(4));
my.setSecondName(cursor.getString(5));
my.setDateofBirth(cursor.getString(6));
my.setMobileNumber(cursor.getString(7));
my.setGender(cursor.getString(8));
my.setGroupAccountNo(cursor.getString(9));
my.setCreatedBy(cursor.getString(10));
my.setResidence(cursor.getString(11));
member_list.add(my);
} while (cursor.moveToNext());
}
cursor.close();
} catch (NumberFormatException e) {
e.printStackTrace();
}
for ( n = 0; n < member_list.size(); n++) {
POST(url, member_list.get(n));
}
db.close();
return String.valueOf(member_list);
}
//onPostExecute displays the results of the AsyncTask.
//Response format
//Response:{"ResponseCode":"00","ResponseMsg":"Successful"}
//Response:{"ResponseCode":"01","ResponseMsg":"Failed"}
#Override
protected void onPostExecute (String result){
prgDialog.dismiss();
Toast.makeText(getBaseContext(),"Saved Successfully",Toast.LENGTH_LONG).show();
dbs = new MainDB(SyncMembersActivity.this);
db = dbs.getWritableDatabase();
String updateQuery = "Update tbl_memberData set sync_status = '" + statusY + "' where account_status='" + account_statusY + "'";
db.execSQL(updateQuery);
String success="";
String message="";
try {
JSONObject jsonBreaker = new JSONObject(result);
success = jsonBreaker.getString("ResponseCode");
message = jsonBreaker.getString("ResponseMsg");
if (success.equalsIgnoreCase("00")) {
prgDialog.dismiss();
showAlert(message);
} else if (success.equalsIgnoreCase("01")) {
prgDialog.dismiss();
//do
showAlert(message);
} else {
prgDialog.dismiss();
Toast.makeText(getBaseContext(), "Error, Please try again...", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setTitle("Response from Server")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
}
});
AlertDialog alert = builder.create();
alert.show();
}
public boolean isNetworkAvailable(final Context context) {
final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
}
If you would baste stacktrace and opoint where rxception is thrown would be much easier.
Anyway
Your result is probably and JSONArray not an JSONObject so this
JSONObject jsonBreaker = new JSONObject(result);
Is causing the exception. Construct JSONArray insteed of JSONObject and this shoult be fine (this is my blind guess cuz no viable info here)

Resources