How do I access the getter methods of a nested custom object? I am able to extract the methods which return Strings but not able to extract methods of a nested object.
My implementation is as follows:
public class DataExtraction {
public void showTheData(Object student) throws IOException {
Class classofStudent = student.getClass();
Method[] methodsOfStudent = classofStudent.getDeclaredMethods();
for(Method method:methodsOfStudent)
{
if(isGetType(method))
{
if(method.getReturnType()==String.class)
{
try(InputStream is = new FileInputStream("ObjectFileReaderPrimitive.properties"))
{
//InputStream is = new FileInputStream("ObjectFileReaderPrimitive.properties");
Properties properties = new Properties();
properties.load(is);
System.out.println(properties.getProperty(method.getName()));
}
}
else
try(InputStream is = new FileInputStream("ObjectFileReaderNonPrimitive.properties"))
{
Class innerObjectClass = method.getReturnType().getClass();
Method[] methodsOfinnerObject = innerObjectClass.getDeclaredMethods();
for(Method methodofInnerClass : methodsOfinnerObject) {
if(isGetType(method))
{
Properties properties = new Properties();
properties.load(is);
System.out.println(properties.getProperty(methodofInnerClass.getName()));
}
}}
}
}}
private boolean isGetType(Method method) {
if(method.getName().startsWith("get"))
return true;
return false;
}
}
Where the student class is as follows-:
package com.sample;
public class Student {
private String id;
private String section;
private Address address;
public Student(String id, String section, Address address) {
super();
this.id = id;
this.section = section;
this.address = address;
}
public Student() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
#Override
public String toString() {
return "Student [id=" + id + ", section=" + section + ", address=" + address + "]";
}
}
Address Object-:
package com.sample;
public class Address {
private String AddressLine1;
private String AddressLine2;
private String AddressLine3;
public Address(String addressLine1, String addressLine2, String addressLine3) {
super();
AddressLine1 = addressLine1;
AddressLine2 = addressLine2;
AddressLine3 = addressLine3;
}
public Address() {
super();
}
public String getAddressLine1() {
return AddressLine1;
}
public void setAddressLine1(String addressLine1) {
AddressLine1 = addressLine1;
}
public String getAddressLine2() {
return AddressLine2;
}
public void setAddressLine2(String addressLine2) {
AddressLine2 = addressLine2;
}
public String getAddressLine3() {
return AddressLine3;
}
public void setAddressLine3(String addressLine3) {
AddressLine3 = addressLine3;
}
#Override
public String toString() {
return "Address [AddressLine1=" + AddressLine1 + ", AddressLine2=" + AddressLine2 + ", AddressLine3="
+ AddressLine3 + "]";
}
}
Your problem is that you are not actually getting the correct class for your inner custom object.
Currently you are doing:
Class innerObjectClass = method.getReturnType().getClass();
This does not work because the method getReturnType is already returning the Class object of the return type. So what is happening is you are calling getClass() on a class object. This will return class java.lang.Class. You just need to remove the call to getClass:
Class innerObjectClass = method.getReturnType();
Here I have modified your code so that it prints all the getter objects in Student and Address
Class classofStudent = Student.class;
Method[] methodsOfStudent = classofStudent.getDeclaredMethods();
for (Method method : methodsOfStudent) {
if (isGetType(method)) {
if (method.getReturnType() == String.class) {
System.out.println(method.getName());
} else {
Class innerObjectClass = method.getReturnType();
Method[] methodsOfinnerObject = innerObjectClass.getDeclaredMethods();
for (Method methodofInnerClass : methodsOfinnerObject) {
if (isGetType(method)) {
System.out.println(methodofInnerClass.getName());
}
}
}
}
}
Related
I have a body return this:
{
"a_name": "Max",
"a_surname": "Miles",
"a_details": {
"DETAILS": [
{
"DATE": "1996-12-31T00:00:00.000",
"AGE": "24",
"ACCNUM": "17",
"FORSPEC": "Smth written here",
"EXIT": "1"
}, ] //list of json
}
By now I am able to return name and surname, but having trouble mapping json field. Here is how my POJO looks like:
class Value {
String name;
String surname;
List<AccountDetail> detail;
//setter getter
}
class AccountDetail {
LocalDateTime DATE;
Number AGE;
Number ACCNUM;
String FORSPEC;
Number EXIT;
//setter getter
}
Here is a mapper for this field:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(
DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
List<AccountDetails> details = mapper.readValue(stringJson, Value.class);
But I am getting errors like unrecognized fields and so on. What is a problem? Maybe I should realize my POJO class in other way or I have a problem with mapper?
You can use Jackson library for Json reading, and use annotation for different name #JsonProperty("a_name")
Few more issues I found in your code:
This is incorrect - List<AccountDetail> detail
You should declare a field DETAILS, as a new class, and inside should be the list.
Also "EXIT" field is missing in the class you defined.
Full working example.
public String test() throws JsonProcessingException
{
String json = "your json here....";
ObjectMapper mapper = new ObjectMapper();
mapper.setDefaultPrettyPrinter(new PrettyPrinter());
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping();
mapper.registerModule(new ParameterNamesModule())
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule());
mapper.readValue(json, Value.class);
return "success";
}
public static class PrettyPrinter extends DefaultPrettyPrinter
{
private static final long serialVersionUID = 1L;
public PrettyPrinter()
{
indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);
}
}
private static class Value
{
#JsonProperty("a_name")
String name;
#JsonProperty("a_surname")
String surname;
#JsonProperty("a_details")
Details details;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getSurname()
{
return surname;
}
public void setSurname(String surname)
{
this.surname = surname;
}
public Details getDetails()
{
return details;
}
public void setDetails(Details details)
{
this.details = details;
}
}
private static class Details
{
#JsonProperty("DETAILS")
AccountDetail []detail;
public AccountDetail[] getDetail()
{
return detail;
}
public void setDetail(AccountDetail[] detail)
{
this.detail = detail;
}
}
private static class AccountDetail
{
LocalDateTime DATE;
Number AGE;
Number ACCNUM;
String FORSPEC;
Number EXIT;
public LocalDateTime getDATE()
{
return DATE;
}
public void setDATE(LocalDateTime DATE)
{
this.DATE = DATE;
}
public Number getAGE()
{
return AGE;
}
public void setAGE(Number AGE)
{
this.AGE = AGE;
}
public Number getACCNUM()
{
return ACCNUM;
}
public void setACCNUM(Number ACCNUM)
{
this.ACCNUM = ACCNUM;
}
public String getFORSPEC()
{
return FORSPEC;
}
public void setFORSPEC(String FORSPEC)
{
this.FORSPEC = FORSPEC;
}
public Number getEXIT()
{
return EXIT;
}
public void setEXIT(Number EXIT)
{
this.EXIT = EXIT;
}
}
You can used Gson library
public class JsonFormater {
public static void main(String[] args) {
Gson gs = new Gson();
// TODO Auto-generated method stub
String jsonstring = "{\n" + " \"a_name\":\"Max\",\n" + " \"a_surname\":\"Miles\",\n"
+ " \"a_details\":{\n" + " \"DETAILS\":[\n" + " {\n"
+ " \"DATE\":\"1996-12-31T00:00:00.000\",\n" + " \"AGE\":\"24\",\n"
+ " \"ACCNUM\":\"17\",\n" + " \"FORSPEC\":\"Smth written here\",\n"
+ " \"EXIT\":\"1\"\n" + " }\n" + " ]\n" + " }\n" + "}";
Information infomation = gs.fromJson(jsonstring, Information.class);
System.out.println(infomation.getaName());
System.out.println(infomation.getaSurname());
if (infomation.getaDetails() != null) {
TestData testdata = infomation.getaDetails();
for (Detail detail : testdata.getDetails()) {
System.out.println(detail.getAge());
}
}
}
}
public class Detail {
#SerializedName("DATE")
#Expose
private String date;
#SerializedName("AGE")
#Expose
private String age;
#SerializedName("ACCNUM")
#Expose
private String accnum;
#SerializedName("FORSPEC")
#Expose
private String forspec;
#SerializedName("EXIT")
#Expose
private String exit;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getAccnum() {
return accnum;
}
public void setAccnum(String accnum) {
this.accnum = accnum;
}
public String getForspec() {
return forspec;
}
public void setForspec(String forspec) {
this.forspec = forspec;
}
public String getExit() {
return exit;
}
public void setExit(String exit) {
this.exit = exit;
}
}
public class TestData {
#SerializedName("DETAILS")
#Expose
private List<Detail> details = null;
public List<Detail> getDetails() {
return details;
}
public void setDetails(List<Detail> details) {
this.details = details;
}
}
public class Information {
#SerializedName("a_name")
#Expose
private String aName;
#SerializedName("a_surname")
#Expose
private String aSurname;
#SerializedName("a_details")
#Expose
private TestData aDetails;
public String getaName() {
return aName;
}
public void setaName(String aName) {
this.aName = aName;
}
public String getaSurname() {
return aSurname;
}
public void setaSurname(String aSurname) {
this.aSurname = aSurname;
}
public TestData getaDetails() {
return aDetails;
}
public void setaDetails(TestData aDetails) {
this.aDetails = aDetails;
}
}
format your json correctly and try like this
I have tried to reorganised my database by adding a child called ("Reviews") that should include reviews added by the users but I keep getting a null displayed on the screen. I can only assume that the variables have not been saved into my modal class. I thought that my calling getReview() in my modal class should work:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(); // getReference() is the root
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Information info = snapshot.getValue(Information.class);
assert info != null;
String txt = "Medical Clinic: " + info.getName() + " \n\n " + "Review: " + info.getReview() + "\n\nServices Provided: " + info.getDorevitch() + " : " + info.getSkin_Cancer() + " : " + info.getEar_Suctioning();
list.add(txt);
// list.add(snapshot.getValue().toString());
}
adapter.notifyDataSetChanged();
}
This is my modal class
enter code hepublic class Information { // variables have to match in firebase database or it will show null
private String Address;
private String Name;
private String Phone_No;
private String Suburb;
private String State;
private String Postcode;
private String Doctor;
private String Dorevitch;
private String Skin_Cancer;
private String Ear_Suctioning;
private String Reviews;
public Information() {
}
public Information(String address, String name, String phone_No, String suburb, String state, String postcode, String dorevitch, String skin_cancer, String ear_suctioning, String doctor, String review) {
Address = address;
Name = name;
Phone_No = phone_No;
Suburb = suburb;
State = state;
Postcode = postcode;
Doctor = doctor;
Dorevitch = dorevitch;
Skin_Cancer = skin_cancer;
Ear_Suctioning = ear_suctioning;
Reviews = review;
}
public String getDorevitch() {
return Dorevitch;
}
public void setDorevitch(String dorevitch) {
Dorevitch = dorevitch;
}
public String getSkin_Cancer() {
return Skin_Cancer;
}
public void setSkin_Cancer(String skin_Cancer) {
Skin_Cancer = skin_Cancer;
}
public String getEar_Suctioning() {
return Ear_Suctioning;
}
public void setEar_Suctioning(String ear_Suctioning) {
Ear_Suctioning = ear_Suctioning;
}
public String getState() {
return State;
}
public void setState(String state) {
State = state;
}
public String getDoctor() {
return Doctor;
}
public void setDoctor(String doctor) {
Doctor = doctor;
}
public String getSuburb() {
return Suburb;
}
public void setSuburb(String suburb) {
Suburb = suburb;
}
public String getReview() {
return Reviews;
}
public void setReview(String review) {
Reviews = review;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPhone_No() {
return Phone_No;
}
public void setPhone_No(String phone_No) {
Phone_No = phone_No;
}
public String getPostcode() {
return Postcode;
}
public void setPostcode(String postcode) {
Postcode = postcode;
}
I can get it to work but don't know why it is only working if I pull out from the database by doing the following code and not using my modal class?
String reviews = String.valueOf(snapshot.child("Reviews").getValue());
String services = String.valueOf(snapshot.child("Services").getValue());
What is the difference between String.valueof and toString()?
I am currently working on mapping a DTO that has two "sub DTOS".
eg.
PersonDTO has "firstName" ,"lastName", "languageDTO", "zipCodeDTO"
now in my PersonMapper I want to use my "LanguageMapper" and my "ZipCodeMapper".
but with #Mapper(uses = "") I am only able to invoke one single outside mapper to use in my class.
Thank you in advance for help
Here is the Code of my DTOs
This is my ZipCodeDTO:
class ZipCodeDTO {
public static final String FIELD_SEPARATOR = "__";
private String favouriteZipCode;
private String cityName;
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFavouriteZipCode() {
return favouriteZipCode;
}
public void setFavouriteZipCode(String favouriteZipCode) {
this.favouriteZipCode = favouriteZipCode;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
#Override
public String toString() {
return id + FIELD_SEPARATOR + favouriteZipCode + FIELD_SEPARATOR + cityName;
}
}
and this is my PersonDTO:
class PersonDTO
{
public static final String FIELD_SEPARATOR = "__";
private int id;
private String firstName;
private String lastName;
private PictureDTO pictureDTO = new PictureDTO();
private ZipCodeDTO zipCodeDTO = new ZipCodeDTO();
private List<PersonLanguageDTO> personLanguageDTOList = new ArrayList<>();
public List<PersonLanguageDTO> getPersonLanguageDTOList() {
return personLanguageDTOList;
}
public void setPersonLanguageDTOList(List<PersonLanguageDTO> personLanguageDTOList) {
this.personLanguageDTOList = personLanguageDTOList;
}
public PictureDTO getPictureDTO() {
return pictureDTO;
}
public void setPictureDTO(PictureDTO pictureDTO) {
this.pictureDTO = pictureDTO;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public ZipCodeDTO getZipCodeDTO() {
return zipCodeDTO;
}
public void setZipCodeDTO(ZipCodeDTO zipCodeDTO) {
this.zipCodeDTO = zipCodeDTO;
}
}
and this is my PersonLanguageDTO
class PersonLanguageDTO{
public static final String FIELD_SEPARATOR = "__";
private String knowledge;
private int personId;
private LanguageDTO languageDTO = new LanguageDTO();
public String getKnowledge() {
return knowledge;
}
public void setKnowledge(String knowledge) {
this.knowledge = knowledge;
}
public int getPersonId() {
return personId;
}
public void setPersonId(int personId) {
this.personId = personId;
}
public LanguageDTO getLanguageDTO() {
return languageDTO;
}
public void setLanguageDTO(LanguageDTO languageDTO) {
this.languageDTO = languageDTO;
}
#Override
public String toString() {
return knowledge + FIELD_SEPARATOR + personId + FIELD_SEPARATOR + languageDTO;
}
}
This, I tried so far
#Mapper (componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.ERROR, uses = ZipCodeMapper.class +PersonLanguageMapper.class)
public interface PersonMapper {
#Mappings({
#Mapping(source = "zipCode" , target = "zipCodeDTO" ),
#Mapping(source = "", target = "pictureDTO")
})
PersonDTO toDTO(Person person);
}
You can add multiple Mappers in uses if you put them in an array:
#Mapper (componentModel = "spring",
unmappedTargetPolicy = ReportingPolicy.ERROR,
uses = { ZipCodeMapper.class, PersonLanguageMapper.class })
public interface PersonMapper {
// Your code here
}
call.enqueue(new Callback<Resul>() {
#Override
public void onResponse(Call<Resul> call, Response<Resul> response) {
progressDialog.dismiss();
Log.d("response", "code = " + response.code());
Log.d("mvvvv","StudentId : "+response.body().toString());
String h=response.body().toString();
if("1".equals(h)){
Intent i = new Intent(Login.this,MainActivity.class);
startActivity(i);
}
else {
Toast.makeText(getApplicationContext()," user name not valid " , Toast.LENGTH_LONG).show();
}
}
Pojo class
package com.example.admin.myappl.Interface;
public class Resul {
private User_info user_info;
private Response Response;
public User_info getUser_info ()
{
return user_info;
}
public void setUser_info (User_info user_info)
{
this.user_info = user_info;
}
public Response getResponse ()
{
return Response;
}
public void setResponse (Response Response)
{
this.Response = Response;
}
public String toString() {
return ""+Response+"";
}
public class Response
{
private String response_message;
private String response_code;
public String getResponse_message ()
{
return response_message;
}
public void setResponse_message (String response_message)
{
this.response_message = response_message;
}
public String getResponse_code ()
{
return response_code;
}
public void setResponse_code (String response_code)
{
this.response_code = response_code;
}
#Override
public String toString()
{
return response_code;
}
}
public class User_info
{
private String profile_picture;
private String lastweek_command;
private String weight;
private String student_id;
private String push_notification_status;
private String id;
private String first_name;
private String updated_at;
private String height;
private String blood_group;
private String email;
private String address;
private String dob;
private String last_name;
private String gender;
private String general_command;
private String activity;
private String mobile_no;
public String getProfile_picture ()
{
return profile_picture;
}
public void setProfile_picture (String profile_picture)
{
this.profile_picture = profile_picture;
}
public String getLastweek_command ()
{
return lastweek_command;
}
public void setLastweek_command (String lastweek_command)
{
this.lastweek_command = lastweek_command;
}
public String getWeight ()
{
return weight;
}
public void setWeight (String weight)
{
this.weight = weight;
}
public String getStudent_id ()
{
return student_id;
}
public void setStudent_id (String student_id)
{
this.student_id = student_id;
}
public String getPush_notification_status ()
{
return push_notification_status;
}
public void setPush_notification_status (String push_notification_status)
{
this.push_notification_status = push_notification_status;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getFirst_name ()
{
return first_name;
}
public void setFirst_name (String first_name)
{
this.first_name = first_name;
}
public String getUpdated_at ()
{
return updated_at;
}
public void setUpdated_at (String updated_at)
{
this.updated_at = updated_at;
}
public String getHeight ()
{
return height;
}
public void setHeight (String height)
{
this.height = height;
}
public String getBlood_group ()
{
return blood_group;
}
public void setBlood_group (String blood_group)
{
this.blood_group = blood_group;
}
public String getEmail ()
{
return email;
}
public void setEmail (String email)
{
this.email = email;
}
public String getAddress ()
{
return address;
}
public void setAddress (String address)
{
this.address = address;
}
public String getDob ()
{
return dob;
}
public void setDob (String dob)
{
this.dob = dob;
}
public String getLast_name ()
{
return last_name;
}
public void setLast_name (String last_name)
{
this.last_name = last_name;
}
public String getGender ()
{
return gender;
}
public void setGender (String gender)
{
this.gender = gender;
}
public String getGeneral_command ()
{
return general_command;
}
public void setGeneral_command (String general_command)
{
this.general_command = general_command;
}
public String getActivity ()
{
return activity;
}
public void setActivity (String activity)
{
this.activity = activity;
}
public String getMobile_no ()
{
return mobile_no;
}
public void setMobile_no (String mobile_no)
{
this.mobile_no = mobile_no;
}
#Override
public String toString()
{
return "ClassPojo [profile_picture = "+profile_picture+", lastweek_command = "+lastweek_command+", weight = "+weight+", student_id = "+student_id+", push_notification_status = "+push_notification_status+", id = "+id+", first_name = "+first_name+", updated_at = "+updated_at+", height = "+height+", blood_group = "+blood_group+", email = "+email+", address = "+address+", dob = "+dob+", last_name = "+last_name+", gender = "+gender+", general_command = "+general_command+", activity = "+activity+", mobile_no = "+mobile_no+"]";
}
}
}
Instead of
String h=response.body().toString();
Use
Resul result = response.body();
If condition should be like this
if("1".equals(result.getResponse().getResponse_code())
Use http://www.jsonschema2pojo.org/ to generate pojo class
If you are using gson for parsing the #SerializedName("your_key") ,
#Expose these 2 tags are required. Otherwise those values will be null
I have a Spring MVC application that handle Users and Structures that can hosts one or more User.
I'm using Hibernate for the persistence and I'm having some issues with the One-To-Many relation between User and Structure.
This is my User model:
#Entity
#Table(name="USERS")
public class User extends DatabaseEntity {
#Id #GeneratedValue
private Long id = 0L;
#Column
#NotEmpty
private String firstName;
#Column
private String lastName;
#Column
private Date birthDate;
#Column
private String nation;
#Column
private String town;
#Column
private String idNumber;
#Column(unique = true)
private String email;
#Column String resetPasswordToken = "";
#Column
private String password;
#Column
private String avatarUrl;
#Column #Enumerated(EnumType.STRING)
private Role role;
#ManyToOne
#JoinColumn(name = "STRUCTURE_ID")
#Cascade({CascadeType.DETACH})
private Structure structure;
public enum Role {
ADMINISTRATOR,
SPECIALIST,
PATIENT,
DOCTOR,
CARE_GIVER
}
public User() {
birthDate = new Date();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getNation() {
return nation;
}
public void setNation(String nation) {
this.nation = nation;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
public String getIdNumber() {
return idNumber;
}
public void setIdNumber(String idNumber) {
this.idNumber = idNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public Set<Group> getGroups() {
return null;
}
public void setGroups(Set<Group> groups) {
}
public Set<Group> getCreatedGroups() {
return null;
}
public void setCreatedGroups(Set<Group> createdGroups) {
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Set<HangoutUser> getHangoutUsers() {
return null;
}
public void setHangoutUsers(Set<HangoutUser> hangoutUsers) {
}
public String getResetPasswordToken() {
return resetPasswordToken;
}
public void setResetPasswordToken(String resetPasswordToken) {
this.resetPasswordToken = resetPasswordToken;
}
public Group getStructure() {
return structure;
}
public void setStructure(Structure structure) {
this.structure = structure;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User)) return false;
User user = (User) o;
if (!email.equals(user.email)) return false;
if (!id.equals(user.id)) return false;
return true;
}
#Override
public int hashCode() {
Long res = id;
if(id == null)
res = 0L;
int result = res.hashCode();
result = 31 * result + email.hashCode();
return result;
}
}
And this is my Structure model:
#Entity
#Table(name = "STRUCTURES")
public class Structure extends DatabaseEntity {
#Id #GeneratedValue
Long id = 0L;
#Column
String name;
#Column
String address;
#Column
String city;
#Column
String state;
#OneToMany(mappedBy = "structure", fetch = FetchType.EAGER)
#Cascade({CascadeType.DELETE})
Set<User> users = new HashSet<User>();
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;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public String getState()
{
return state;
}
public void setState(String state)
{
this.state = state;
}
public Set<User> getUsers()
{
return this.users;
}
public void setUsers(Set<User> users)
{
this.users = users;
}
}
My issue is that when I try to find all the Users with the value STRUCTURE_ID evaluated, I get an Hibernate Exception, like this:
org.springframework.orm.hibernate3.HibernateSystemException: Found two representations of same collection: it.amtservices.livinglab.model.Group.users; nested exception is org.hibernate.HibernateException: Found two representations of same collection: it.amtservices.livinglab.model.Structure.users
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:690) ...
What should I do to solve this problem? I have already tried many ways but nothing solved.
I paste the abstract repository implementation for the UsersRepository and StructureRepository:
#Transactional
public abstract class AbstractRepository<Model extends DatabaseEntity>
{
Logger logger = Logger.getLogger(this.getClass().getSimpleName());
#PersistenceContext
EntityManager em;
protected Class<Model> ModelClass;
protected List<Model> findBy(String parameterName, Object parameterValue)
{
Query q = em.createQuery("select t from " + ModelClass.getSimpleName() + " t where t." + parameterName + " = :" + parameterName);
q.setParameter(parameterName, parameterValue);
List<Model> results = null;
try
{
results = q.getResultList();
}
catch (Exception e)
{
return null;
}
return results;
}
protected List<Model> findBy(Map<String, Object> parameters)
{
String whereClause = "";
for (String key : parameters.keySet())
{
if (!whereClause.equals("")) whereClause += " and ";
whereClause += "t." + key + " = :" + key;
}
Query q = null;
try
{
q = em.createQuery("select t from " + ModelClass.getSimpleName() + " t where " + whereClause);
}
catch (Exception e)
{
e.printStackTrace();
}
for (String key : parameters.keySet())
{
q.setParameter(key, parameters.get(key));
}
List<Model> results = null;
try
{
results = q.getResultList();
}
catch (Exception e)
{
return null;
}
return results;
}
protected Model findOneBy(String parameterName, Object parameterValue)
{
List<Model> results = findBy(parameterName, parameterValue);
if (results != null && results.size() > 0) return results.get(0);
return null;
}
protected Model findOneBy(Map<String, Object> parameters)
{
List<Model> results = findBy(parameters);
if (results != null && results.size() > 0) return results.get(0);
return null;
}
public Model findOne(Long id)
{
return findOneBy("id", id);
}
public List<Model> findAll()
{
Query q = em.createQuery("select t from " + ModelClass.getSimpleName() + " t");
List<Model> results = null;
try
{
results = q.getResultList();
}
catch (Exception e)
{
return null;
}
return results;
}
public boolean save(Model model)
{
try
{
Model newModel = em.merge(model);
if (model.getId() == 0L) model.setId(newModel.getId());
}
catch (Exception e)
{
logger.error(ModelClass.getSimpleName() + "Repository: " + e.getMessage());
return false;
}
return true;
}
public void save(List<Model> models)
{
for (Model model : models)
{
save(model);
}
}
public void delete(Model model)
{
delete(model.getId());
}
public void delete(Long id)
{
beforeDelete(findOne(id));
try
{
Query q = em.createQuery("delete from " + ModelClass.getSimpleName() + " t where t.id = :id").setParameter("id", id);
q.executeUpdate();
}
catch (Exception e)
{
logger.error(ModelClass.getSimpleName() + "Repository: " + e.getMessage());
}
}
public void delete(Collection<Model> models)
{
for (Model model : models)
{
delete(model.getId());
}
}
public void deleteAll()
{
for (Model model : findAll())
{
delete(model);
}
}
public abstract void beforeDelete(Model model);
public List<Model> find(List<Long> ids)
{
List<Model> models = new ArrayList<Model>();
for (Long id : ids)
{
Model model = findOne(id);
if (model != null) models.add(model);
}
return models;
}
}
Thank you!