how to convert integer to string using typeconverters in room android? - android-room

I am developing a chat app but I am getting the following error: Cannot find getter for the field.
that's why I want to convert Integer to String using type converters in Room but I did not find any sample below my User.java model class
#Entity public class User implements IChatUser {
#PrimaryKey(autoGenerate = true)
private Integer id;
#ColumnInfo(name = "name")
private String name;
#Ignore
Bitmap icon;
public User() {
}
#Ignore
public User(String name, Bitmap icon) {
this.name = name;
this.icon = icon;
}
#Override
public Integer getId() {
return this.id;
}
#Override
public String getName() {
return this.name;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
#Override
public Bitmap getIcon() {
return this.icon;
}
#Override
public void setIcon(Bitmap icon) {
this.icon = icon;
} }
below IchatUser.kt
interface IChatUser {
fun getId(): String
fun getName(): String?
fun getIcon(): Bitmap?
fun setIcon(bmp: Bitmap)
}

To create a #TypeConverter create a java class and call it IntConverter
public class IntConverter {
#TypeConverter
public static String toString(int number) {
return number == null ? null : Integer.toString(number);
}
#TypeConverter
public static int toInt(String str) {
return str == null ? null : Integer.parseInt(str);
}
}
Now you need the database to know about this TypeConverter so declare this:
#TypeConverters(IntConverter.class)
Just below the #Database annotation in the Database class

Related

Spring Boot Rest

i am practicing with spring boot for work with restful applications
I have set a #RestController and #Entity like this
#RestController
#RequestMapping(value = "/api")
public class RestControllerCar {
#Autowired
private CarRepository carRepository;
#RequestMapping(value = "/cars")
public Iterable<Car> getCars() {
return carRepository.findAll();
}
}
and
#Entity
public class Car {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String brand, model, color, registerNumber;
private Integer year, price;
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#ManyToMany(mappedBy = "cars")
private Set<Owner> owners;
public Car() {
}
public Car(String brand, String model, String color, String registerNumber, Integer year, Integer price) {
super();
this.brand = brand;
this.model = model;
this.color = color;
this.registerNumber = registerNumber;
this.year = year;
this.price = price;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getRegisterNumber() {
return registerNumber;
}
public void setRegisterNumber(String registerNumber) {
this.registerNumber = registerNumber;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Set<Owner> getOwner() {
return owners;
}
public void setOwner(Set<Owner> owners) {
this.owners = owners;
}
when i use postman to http://localhost:8080/cardatabase/api/cars i get a list of Cars
but even if i go to http://localhost:8081/cardatabase/cars, with _embedded on the top
it`s normal?
Thanks!!!!
Is your repository annotated #RestRepository? The _embedded make me think to the kind of output given by a #RestRepository for an array.
#RestRepository auto create all endpoint. As #M.Deinum pointed out, with the data rest starter, if ou remove it , you only have your controller, and not the one generated by #RestRepository.
Two main choices here:
You dont annotate the Repository. Just an interface which implement JpaRepository<YourEntity, TypeOfYourID> and use your controllers
You use only the auto created controllers by #RestRepository.
Or, you can install swagger2 on your project, so, accessing the docs on your browser, you will see all available endpoints, and it may be more clear for you.
With swagger you will also see what is the return type of the endpoint, the parameters etc..
Swagger is really easy to install in a project and to use. (dependencies, one annotation and it's good.. for basic usage).

How to create a custom json object to columns value returned from my custom #Query

I have a query to My SQL database and I use Spring Boot to return it to Json format.
My problem is it only return value without key like:
[
[
"kermit",
6
]
]
I want it return like:
[
[
"name":"kermit",
"count" :6
]
]
I tried add Jackson Annotation jar file to project and use #JsonProperty in my entity model class:
#Entity
#Table(name = "act_id_membership", schema = "activiti", catalog = "")
#IdClass(ActIdMembershipEntityPK.class)
public class ActIdMembershipEntity {
#JsonProperty("name")
private String userId;
#JsonProperty("group")
private String groupId;
#Id
#Column(name = "USER_ID_")
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Id
#Column(name = "GROUP_ID_")
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ActIdMembershipEntity that = (ActIdMembershipEntity) o;
return Objects.equals(userId, that.userId) &&
Objects.equals(groupId, that.groupId);
}
#Override
public int hashCode() {
return Objects.hash(userId, groupId);
}
}
But it still return without key. What I should do now? Please help me!
Thank you very much!
First, I'm agree with guy who commented that is not valid JSON format. You can see examples here https://json.org/example.html
Second, You need to create an object JSON which has fields needed for example:
public class UserStat es implements Serializable {
private String name;
private long count;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
}
And in your custom query. Based your return looks like on this way:
#Query("SELECT u.name, count(u) FROM User u")
public List<UserStat> findUserStat() ;

Error Spring React REST Controller Using Custom Class Response (WebFlux)

I'm trying to build a Spring WebFlux project and realize the follow business logic:
1 - Call an external REST Api using WebClient and parse the Json results using the Models below. It is working OK
2 - To show the Mono results Mono<DeviceList> devices, I'm using the ResponseApi class and returning it, but it is NOT working
I'm getting the follow error:
Response status 406 with reason "Could not find acceptable representation"
Thanks
# Json Result
{
"data": [
{
"id": "5bc3c0efe833d93f401bafa8",
"name": "XXXXX",
"group": "5b8fd1fa0499f54cfa7febb8",
"description": "Geolocalizacao gps",
"payloadType": "None",
"contract": "5bc08be5e833d93f40e1f936",
"keepAlive": 0
}
]
}
# Controller
public class DeviceController{
...
...
#RequestMapping(value = V1 + BASE_URL + "/devices/types", method = GET, produces = APPLICATION_JSON)
public Mono<ServerResponse> getDeviceTypes(){
Mono<DeviceList> devices = deviceService.findDeviceTypes();
ResponseApi r = new ResponseApi();
r.setMessage("Test");
r.setCode("200");
r.setStatus(200);
r.setData(devices);
return ok().body(Mono.just(r), ResponseApi.class);
}
}
# Repository
public Mono<DeviceList> findDeviceTypes() {
return webClient.get()
.uri(DEVICE_TYPES_URL)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(DeviceList.class);
}
# Model
public class DeviceList{
#JsonProperty("data")
private List<Device> data;
public List<Device> getData() {
return data;
}
public void setData(List<Device> data) {
this.data = data;
}
}
public class Device{
#JsonProperty("id")
private String id;
#JsonProperty("name")
private String name;
#JsonProperty("group")
private String group;
#JsonProperty("description")
private String description;
#JsonProperty("keepAlive")
private Integer keepAlive;
#JsonProperty("payloadType")
private String payloadType;
#JsonProperty("contract")
private String contract;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getKeepAlive() {
return keepAlive;
}
public void setKeepAlive(Integer keepAlive) {
this.keepAlive = keepAlive;
}
public String getPayloadType() {
return payloadType;
}
public void setPayloadType(String payloadType) {
this.payloadType = payloadType;
}
public String getContract() {
return contract;
}
public void setContract(String contract) {
this.contract = contract;
}
}
#JsonRootName("data")
public class ResponseApi{
#JsonProperty("status")
private Integer status;
#JsonProperty("code")
private String code;
#JsonProperty("message")
private String message;
#JsonProperty("data")
private Object data;
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
You can get devices, then in non blocking way, map them to the ResponseApi like that:
#RequestMapping(value = V1 + BASE_URL + "/devices/types", method = GET, produces = APPLICATION_JSON)
public Mono<ServerResponse> getDeviceTypes(){
return deviceService.findDeviceTypes()
.flatMap(devices -> {
ResponseApi r = new ResponseApi();
r.setMessage("Test");
r.setCode("200");
r.setStatus(200);
r.setData(devices);
return ok().body(Mono.just(r), ResponseApi.class);
});
}

Spring mongo repository sort descending by a certain property

I want to sort Descending by lastChange property, the List of items from mongo.
RequestRepository interface:
public interface RequestRepository extends MongoRepository<Request, String> {
List<Request> findByUser(String id);
}
Request.java:
#Document(collection = "Requests")
public class Request {
#Id
private String id;
private String user;
private String username;
private String requestTitle;
private String requestMessage;
private boolean read;
private Date lastChange;
private Date requestDate;
private boolean isActiveRequest;
private boolean isPremiumRequest; //paid request
public Request() {}
public Request(
String user,
String requestTitle,
String requestMessage,
boolean read,
Date lastChange,
Date requestDate,
boolean isActiveRequest) {
this.user = user;
this.requestTitle = requestTitle;
this.requestMessage = requestMessage;
this.read = read;
this.lastChange = lastChange;
this.requestDate = requestDate;
this.isActiveRequest = isActiveRequest;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getRequestTitle() {
return requestTitle;
}
public void setRequestTitle(String requestTitle) {
this.requestTitle = requestTitle;
}
public String getRequestMessage() {
return requestMessage;
}
public void setRequestMessage(String requestMessage) {
this.requestMessage = requestMessage;
}
public boolean isRead() {
return read;
}
public void setRead(boolean read) {
this.read = read;
}
public Date getLastChange() {
return lastChange;
}
public void setLastChange(Date lastChange) {
this.lastChange = lastChange;
}
public Date getRequestDate() {
return requestDate;
}
public void setRequestDate(Date requestDate) {
this.requestDate = requestDate;
}
public boolean isActiveRequest() {
return isActiveRequest;
}
public void setActiveRequest(boolean activeRequest) {
isActiveRequest = activeRequest;
}
public boolean isPremiumRequest() {
return isPremiumRequest;
}
public void setPremiumRequest(boolean premiumRequest) {
isPremiumRequest = premiumRequest;
}
}
In my code I have the following list:
List<Request> = RequestRepository.findByUser(userObj.getId());
I want to have the data from RequestRepository.findByUser(userObj.getId()); sorted DESCENDING by the property lastChange.
I have searched on StackOverflow, and found the following method to sort:
List<Request> findAllByOrderByUpdatedAtDesc();
but this does not work if I search by User.
What is the solution to search by User id and to sort by lastChange?
Thank you!
This should do it.
List<Request> findByUserOrderByLastChangeDesc(String user);
Update your question with proper details.

ManyToMany select query is correct and the query is viewed in console. But I cant put values into jsp

I added many to many relationship to importers and agents table..data save successfully and middle table created...but i cannot retrieve data to my jsp ...How can i retrieve agents table data to my jsp.
My model is
package lk.slsi.domain;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "importers")
public class Importer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "importer_id")
private long importerId;
#NotEmpty
#Column(unique = true, nullable = false)
private String importerBrc;
private String importerVatNumber;
private String importerName;
private String importerAddress1;
private String importerAddress2;
private String importerAddress3;
private String importerCityName;
private String officePhoneNumber;
private String mobilePhoneNumber;
#Email
private String email;
#Email
private String optemail1;
#Email
private String optemail2;
public String getOptemail1() {
return optemail1;
}
public void setOptemail1(String optemail1) {
this.optemail1 = optemail1;
}
public String getOptemail2() {
return optemail2;
}
public void setOptemail2(String optemail2) {
this.optemail2 = optemail2;
}
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinTable(name = "importer_agents",
joinColumns = {#JoinColumn(name = "importerId")},
inverseJoinColumns = {#JoinColumn(name = "agentId")})
private List<Agent> agentList;
public String getImporterBrc() {
return importerBrc;
}
public void setImporterBrc(String importerBrc) {
this.importerBrc = importerBrc;
}
public String getImporterVatNumber() {
return importerVatNumber;
}
public void setImporterVatNumber(String importerVatNumber) {
this.importerVatNumber = importerVatNumber;
}
public String getImporterName() {
return importerName;
}
public void setImporterName(String importerName) {
this.importerName = importerName;
}
public String getImporterAddress1() {
return importerAddress1;
}
public void setImporterAddress1(String importerAddress1) {
this.importerAddress1 = importerAddress1;
}
public String getImporterAddress2() {
return importerAddress2;
}
public void setImporterAddress2(String importerAddress2) {
this.importerAddress2 = importerAddress2;
}
public String getImporterAddress3() {
return importerAddress3;
}
public void setImporterAddress3(String importerAddress3) {
this.importerAddress3 = importerAddress3;
}
public String getImporterCityName() {
return importerCityName;
}
public void setImporterCityName(String importerCityName) {
this.importerCityName = importerCityName;
}
public String getOfficePhoneNumber() {
return officePhoneNumber;
}
public void setOfficePhoneNumber(String officePhoneNumber) {
this.officePhoneNumber = officePhoneNumber;
}
public String getMobilePhoneNumber() {
return mobilePhoneNumber;
}
public void setMobilePhoneNumber(String mobilePhoneNumber) {
this.mobilePhoneNumber = mobilePhoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getImporterId() {
return importerId;
}
public void setImporterId(long importerId) {
this.importerId = importerId;
}
public List<Agent> getAgentList() {
return agentList;
}
public void setAgentList(List<Agent> agentList) {
this.agentList = agentList;
}
}
my agent table model is
package lk.slsi.domain;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
#Entity
#Table(name = "agents")
public class Agent {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "agent_id")
private long agentId;
#NotEmpty
#Column(unique = true, nullable = false)
private String nic;
private String vatNumber;
private String name;
private String agentAddress1;
private String agentAddress2;
private String agentAddress3;
private String agentCityName;
private String officePhoneNumber;
private String mobilePhoneNumber;
#Email
private String email;
public long getAgentId() {
return agentId;
}
public void setAgentId(long agentId) {
this.agentId = agentId;
}
public String getNic() {
return nic;
}
public void setNic(String nic) {
this.nic = nic;
}
public String getVatNumber() {
return vatNumber;
}
public void setVatNumber(String vatNumber) {
this.vatNumber = vatNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAgentAddress1() {
return agentAddress1;
}
public void setAgentAddress1(String agentAddress1) {
this.agentAddress1 = agentAddress1;
}
public String getAgentAddress2() {
return agentAddress2;
}
public void setAgentAddress2(String agentAddress2) {
this.agentAddress2 = agentAddress2;
}
public String getAgentAddress3() {
return agentAddress3;
}
public void setAgentAddress3(String agentAddress3) {
this.agentAddress3 = agentAddress3;
}
public String getAgentCityName() {
return agentCityName;
}
public void setAgentCityName(String agentCityName) {
this.agentCityName = agentCityName;
}
public String getOfficePhoneNumber() {
return officePhoneNumber;
}
public void setOfficePhoneNumber(String officePhoneNumber) {
this.officePhoneNumber = officePhoneNumber;
}
public String getMobilePhoneNumber() {
return mobilePhoneNumber;
}
public void setMobilePhoneNumber(String mobilePhoneNumber) {
this.mobilePhoneNumber = mobilePhoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
my repository is
package lk.slsi.repository;
import java.util.List;
import lk.slsi.domain.Importer;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
/**
* Created by ignotus on 2/8/2017.
*/
public interface ImporterRepository extends CrudRepository<Importer,Long> {
#Override
Importer save(Importer importer);
#Override
Importer findOne(Long importerId);
#Override
List<Importer> findAll();
#Override
void delete(Long aLong);
#Override
void delete(Importer importer);
#Override
void delete(Iterable<? extends Importer> iterable);
#Query("select u from Importer u where u.importerVatNumber = :importerVatNumber")
Importer getImporterByimporterVatNumber(#Param("importerVatNumber") String importerVatNumber);
#Query("select u from Importer u inner join u.agentList where u.importerId = :importerId")
List<Importer> findAgents(#Param("importerId") long importerId);
#Query("select u from Importer u where u.importerId = :importerId")
Importer getImporterByimporterID(#Param("importerId") long importerId);
}
my services is
public List<Importer> getAllIAgents(long importerId) {
return importerRepository.findAgents(importerId);
}
My controller is
#RequestMapping(path = "/viewImporter", method = RequestMethod.POST)
public String updateImporterAll(#RequestParam("importerId") long importerId, Model model) {
slsiLogger.info("Updating user with Id [{}]", importerId);
System.out.println("Importer id is " + importerId);
model.addAttribute("importerDetails", importerServices.getImporterByimporterID(importerId));
model.addAttribute("Agentsdetail", importerServices.getAllIAgents(importerId));
return "importerEdit";
}
Jsp is
<th width="15%">Registered Agents</th>
<c:forEach items="${Agentsdetail}" var="Agent">
<tr>
<td>${Agent.agentList.vatNumber}</td>
</tr>
/c:forEach>
</thead>
The query shows in netbeans console like this
Hibernate: select importer0_.importer_id as importer1_2_, importer0_.email as email2_2_, importer0_.importer_address1 as importer3_2_, importer0_.importer_address2 as importer4_2_, importer0_.importer_address3 as importer5_2_, importer0_.importer_brc as importer6_2_, importer0_.importer_city_name as importer7_2_, importer0_.importer_name as importer8_2_, importer0_.importer_vat_number as importer9_2_, importer0_.mobile_phone_number as mobile_10_2_, importer0_.office_phone_number as office_11_2_, importer0_.optemail1 as optemai12_2_, importer0_.optemail2 as optemai13_2_ from importers importer0_ inner join importer_agents agentlist1_ on importer0_.importer_id=agentlist1_.importer_id inner join agents agent2_ on agentlist1_.agent_id=agent2_.agent_id where importer0_.importer_id=?
How can i insert agent table values to my jsp.Please help me

Resources