I am using Spring MVC and spring take care of converting json to Objects in controller. But my json structure is different then class structure. So I have written my own deserializer. But I am getting problem to accessing values of parent object in JSON. I think it is better to explain my problem using some example -
I have following JSON to deserialize
{
id: 1,
children: {
"name1": "value1",
"name2": "value2"
}
}
I have following classes (Sample Code) -
public class Parent {
private Integer id;
#JsonDeserialize(using= ChildrenDeserializer.class)
private List<Child> children;
//... Getter/setters
}
public class Child {
private Integer id;
private String name;
private String value;
//...getters/setters
}
public class ChildrenDeserializer extends JsonDeserializer<List<Child>> {
#Override
public List<Child> deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
List<Child> children = new ArrayList<>();
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
Iterator<Map.Entry<String, JsonNode>> fieldsIterator = node.fields();
while (fieldsIterator.hasNext()) {
Map.Entry<String, JsonNode> field = fieldsIterator.next();
String name = field.getKey();
String value = field.getValue().textValue();
Child child = new Child();
//Here I want to get parentId from the Json. Is it possible??
Integer childId = childRepository.searchChildIdByParentId(parentId, name);
child.setId(childId);
child.setName(name);
child.setValue(value);
children.add(child);
}
return children;
}
}
Is there any way to get parentId (which is 1 in above example) while deserializing children??
Having the same need , I come across with your question . My solution to the problem is on the parent constructor: When create the parent class, set the correct property in the child class.
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
public class JsonUnitTest {
private static final Logger logger = LogManager.getLogger(JsonUnitTest.class);
#Test
public void unit() {
// test objects
final int parentId = 1;
final int childId = 2;
final ParentClass parent = new ParentClass(parentId);
final ChildClass child = new ChildClass(childId);
parent.setChild(child);
// serialize
final String json = JsonHelper.toJson(parent);
logger.info(json);
logger.info(parent);
// deserialize
final ParentClass newParent = JsonHelper.fromJson(json, ParentClass.class);
// asserts
Assert.assertNotNull(newParent);
Assert.assertEquals(newParent, parent);
}
The result of the test is
[main] INFO JsonUnitTest:29 {"id":1,"child":{"childId":2}}
[main] INFO JsonUnitTest:30 ParentClass [id=1, child=ChildClass [parentId=1, childId=2]]
PASSED: unit
Here the rest of the code :
public static class ParentClass {
public static final String idKey = "id";
public static final String childKey = "child";
#JsonProperty(idKey)
private int id;
#JsonProperty(childKey)
private ChildClass child;
public ParentClass(int id) {
this.id = id;
}
#JsonCreator
public ParentClass(
#JsonProperty(idKey) int id,
#JsonProperty(childKey) ChildClass child) {
super();
this.id = id;
setChild(child);
}
#JsonProperty(idKey)
public int getId() {
return id;
}
#JsonProperty(idKey)
public void setId(int id) {
this.id = id;
}
#JsonProperty(childKey)
public ChildClass getChild() {
return child;
}
#JsonProperty(childKey)
public void setChild(ChildClass child) {
this.child = child;
child.setParentId(id);
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((child == null) ? 0 : child.hashCode());
result = prime * result + id;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ParentClass other = (ParentClass) obj;
if (child == null) {
if (other.child != null)
return false;
} else if (!child.equals(other.child))
return false;
if (id != other.id)
return false;
return true;
}
#Override
public String toString() {
return "ParentClass [id=" + id + ", child=" + child + "]";
}
}
public static class ChildClass {
public static final String parentIdKey = "../" + ParentClass.idKey;
public static final String childIdKey = "childId";
private int parentId;
private int childId;
#JsonCreator
public ChildClass(#JsonProperty(childIdKey) int childId) {
super();
this.childId = childId;
}
#JsonIgnore
public int getParentId() {
return parentId;
}
#JsonProperty(parentIdKey)
public void setParentId(int parentId) {
this.parentId = parentId;
}
#JsonProperty(childIdKey)
public int getChildId() {
return childId;
}
#JsonProperty(childIdKey)
public void setChildId(int childId) {
this.childId = childId;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + childId;
result = prime * result + parentId;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ChildClass other = (ChildClass) obj;
if (childId != other.childId)
return false;
if (parentId != other.parentId)
return false;
return true;
}
#Override
public String toString() {
return "ChildClass [parentId=" + parentId + ", childId=" + childId + "]";
}
}
}
Related
Before java 16 you would use a class with a lombok value annotation, because records didn't exist yet (except in preview). If you wanted a builder and wanted a field to have a default value, you would annotate it like so:
#Builder
#Value
public class SomeClass {
private final int id;
private final String someString;
#Builder.Default
private final String someOtherString = "DefaultVal";
}
This would generate the following class:
public final class SomeClass {
private final int id;
private final String someString;
private final String someOtherString;
SomeClass(int id, String someString, String someOtherString) {
this.id = id;
this.someString = someString;
this.someOtherString = someOtherString;
}
private static String $default$someOtherString() {
return "DefaultVal";
}
public static SomeClassBuilder builder() {
return new SomeClassBuilder();
}
public int getId() {
return this.id;
}
public String getSomeString() {
return this.someString;
}
public String getSomeOtherString() {
return this.someOtherString;
}
public boolean equals(final Object o) {
if (o == this) return true;
if (!(o instanceof SomeClass)) return false;
final SomeClass other = (SomeClass) o;
if (this.getId() != other.getId()) return false;
final Object this$someString = this.getSomeString();
final Object other$someString = other.getSomeString();
if (this$someString == null ? other$someString != null : !this$someString.equals(other$someString))
return false;
final Object this$someOtherString = this.getSomeOtherString();
final Object other$someOtherString = other.getSomeOtherString();
if (this$someOtherString == null ? other$someOtherString != null : !this$someOtherString.equals(other$someOtherString))
return false;
return true;
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
result = result * PRIME + this.getId();
final Object $someString = this.getSomeString();
result = result * PRIME + ($someString == null ? 43 : $someString.hashCode());
final Object $someOtherString = this.getSomeOtherString();
result = result * PRIME + ($someOtherString == null ? 43 : $someOtherString.hashCode());
return result;
}
public String toString() {
return "SomeClass(id=" + this.getId() + ", someString=" + this.getSomeString() + ", someOtherString=" + this.getSomeOtherString() + ")";
}
public static class SomeClassBuilder {
private int id;
private String someString;
private String someOtherString$value;
private boolean someOtherString$set;
SomeClassBuilder() {
}
public SomeClassBuilder id(int id) {
this.id = id;
return this;
}
public SomeClassBuilder someString(String someString) {
this.someString = someString;
return this;
}
public SomeClassBuilder someOtherString(String someOtherString) {
this.someOtherString$value = someOtherString;
this.someOtherString$set = true;
return this;
}
public SomeClass build() {
String someOtherString$value = this.someOtherString$value;
if (!this.someOtherString$set) {
someOtherString$value = SomeClass.$default$someOtherString();
}
return new SomeClass(id, someString, someOtherString$value);
}
public String toString() {
return "SomeClass.SomeClassBuilder(id=" + this.id + ", someString=" + this.someString + ", someOtherString$value=" + this.someOtherString$value + ")";
}
}
}
Now that we are well beyond java 16 and records have been added, I was trying to get this to work with those records. #Builder seems to work fine, but how can I use #Builder.Default with records?
#Builder
public record SomeClass(
int id,
String someString,
#Builder.Default
String someOtherString = "DefaultVal"
) {
}
The above code obviously doesn't work, because you can't assign a value in a record property definition. Is there a way to use #Builder.Default with records? For instance, can #Builder.ObtainVia be used for this or does that really only work with toBuilder()?
If you're looking to solve default values you can use this:
public record SomeClass(
int id,
String someString,
String someOtherString){
public SomeClass(){
this(UUID.randomUUID(), "default","default");
}
}
I am beginner using java and spring jpa (expecially Jhipster). I want to create object in object like this :
But I always get like this :
property buildingsDTO always empty, this is my code, please correct my code in order I get like first picture.
location.java (Domain)
public class Location implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Column(name = "content_location", nullable = false)
private String content_location;
#OneToMany(mappedBy = "location")
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Building> buildings = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getContent_location() {
return content_location;
}
public Location content_location(String content_location) {
this.content_location = content_location;
return this;
}
public void setContent_location(String content_location) {
this.content_location = content_location;
}
public Set<Building> getBuildings() {
return buildings;
}
public Location buildings(Set<Building> buildings) {
this.buildings = buildings;
return this;
}
public Location addBuilding(Building building) {
this.buildings.add(building);
building.setLocation(this);
return this;
}
public Location removeBuilding(Building building) {
this.buildings.remove(building);
building.setLocation(null);
return this;
}
public void setBuildings(Set<Building> buildings) {
this.buildings = buildings;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Location location = (Location) o;
if (location.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), location.getId());
}
#Override
public int hashCode() {
return Objects.hashCode(getId());
}
#Override
public String toString() {
return "Location{" +
"id=" + getId() +
", content_location='" + getContent_location() + "'" +
"}";
}}
locationDTO.java
public class LocationDTO implements Serializable {
private Long id;
#NotNull
private String content_location;
private Set<BuildingDTO> buildings = new HashSet<>();
public Set<BuildingDTO> getBuildingsDTO() {
return buildings;
}
public void setBuildingsDTO(Set<BuildingDTO> buildings) {
this.buildings = buildings;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getContent_location() {
return content_location;
}
public void setContent_location(String content_location) {
this.content_location = content_location;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LocationDTO locationDTO = (LocationDTO) o;
if(locationDTO.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), locationDTO.getId());
}
#Override
public int hashCode() {
return Objects.hashCode(getId());
}
#Override
public String toString() {
return "LocationDTO{" +
"id=" + getId() +
", content_location='" + getContent_location() + "'" +
"}";
}}
locationMapper.java
public interface LocationMapper extends EntityMapper <LocationDTO, Location> {
#Mapping(target = "buildings", ignore = true)
Location toEntity(LocationDTO locationDTO);
default Location fromId(Long id) {
if (id == null) {
return null;
}
Location location = new Location();
location.setId(id);
return location;
}}
buildingDTO.java
public class BuildingDTO implements Serializable {
private Long id;
#NotNull
private String content_building;
private Long locationId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getContent_building() {
return content_building;
}
public void setContent_building(String content_building) {
this.content_building = content_building;
}
public Long getLocationId() {
return locationId;
}
public void setLocationId(Long locationId) {
this.locationId = locationId;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BuildingDTO buildingDTO = (BuildingDTO) o;
if(buildingDTO.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), buildingDTO.getId());
}
#Override
public int hashCode() {
return Objects.hashCode(getId());
}
#Override
public String toString() {
return "BuildingDTO{" +
"id=" + getId() +
", content_building='" + getContent_building() + "'" +
"}";
}}
please anyone help me.
thanks.
By default jHipster will mark any OneToMany entity relationships as #JsonIgnore so that the Set of buildings is not returned in the JSON:
#OneToMany(mappedBy = "location")
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Building> buildings = new HashSet<>();
If you want this to show up in the JSON then you should remove that annotation and also mark it with an eager loading strategy so that the set of buildings are loaded as you expect:
#OneToMany(mappedBy = "location", fetch = FetchType.EAGER)
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Building> buildings = new HashSet<>();
I have an entity question and an entity test with ManyToMany relationship between the two entitie.
when I want to view the questions of a test this error is occurred.
failed to lazily initialize a collection of role:
tn.esen.entities.Test.questions, could not initialize proxy - no Session
this is the JPA implementation of the two entities.
Question:
package tn.esen.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
#Entity
public class Question implements Serializable {
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((contenu == null) ? 0 :
contenu.hashCode());
result = prime * result + ((dateCreation == null) ? 0 :
dateCreation.hashCode());
result = prime * result + ((niveauDeDifficulte == null) ? 0 :
niveauDeDifficulte.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;
Question other = (Question) obj;
if (contenu == null) {
if (other.contenu != null)
return false;
} else if (!contenu.equals(other.contenu))
return false;
if (dateCreation == null) {
if (other.dateCreation != null)
return false;
} else if (!dateCreation.equals(other.dateCreation))
return false;
if (niveauDeDifficulte == null) {
if (other.niveauDeDifficulte != null)
return false;
} else if (!niveauDeDifficulte.equals(other.niveauDeDifficulte))
return false;
return true;
}
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id_question")
private int id;
private String contenu;
private String niveauDeDifficulte;
private Date dateCreation;
#OneToMany(mappedBy="question",fetch = FetchType.EAGER)
private Collection <Reponse> reponses;
#ManyToOne
private Categorie categorie;
#ManyToOne
private Administrateur administrateur;
#ManyToMany(mappedBy = "questions",fetch = FetchType.EAGER)
private Collection<Test> tests;
public Question(){
super();
}
#Override
public String toString() {
return "Question [id=" + id + ", contenu=" + contenu + ",
niveauDeDifficulte=" + niveauDeDifficulte + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getContenu() {
return contenu;
}
public void setContenu(String contenu) {
this.contenu = contenu;
}
public String getNiveauDeDifficulte() {
return niveauDeDifficulte;
}
public void setNiveauDeDifficulte(String niveauDeDifficulte) {
this.niveauDeDifficulte = niveauDeDifficulte;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
public Collection<Reponse> getReponses() {
return reponses;
}
public void setReponses(Collection<Reponse> reponses) {
this.reponses = reponses;
}
public Categorie getCategorie() {
return categorie;
}
public void setCategorie(Categorie categorie) {
this.categorie = categorie;
}
public Administrateur getAdministrateur() {
return administrateur;
}
public void setAdministrateur(Administrateur administrateur) {
this.administrateur = administrateur;
}
public Collection<Test> getTest() {
return tests;
}
public void setTest(Collection<Test> tests) {
this.tests = tests;
}
public Question(String contenu, String niveauDeDifficulte, Date
dateCreation) {
super();
this.contenu = contenu;
this.niveauDeDifficulte = niveauDeDifficulte;
this.dateCreation = dateCreation;
}
Test:
package tn.esen.entities;
#Entity
public class Test implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String duree;
private String typeDePreparation;
private String lieu;
private int nbrQuestionFacile;
private int nbrQuestionMoyen;
private int nbrQuestionDifficle;
#OneToMany(mappedBy = "test")
private Collection<Resultat> resultats;
#ManyToMany
private Collection<Question> questions;
#ManyToOne
private ResponsableTechnique responsableTechnique;
public Test() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDuree() {
return duree;
}
public void setDuree(String duree) {
this.duree = duree;
}
public Collection<Question> getQuestions() {
return questions;
}
public void setQuestions(Collection<Question> questions) {
this.questions = questions;
}
public Test(String duree, String typeDePreparation, String lieu, int
nbrQuestionFacile, int nbrQuestionMoyen,
int nbrQuestionDifficle) {
super();
this.duree = duree;
this.typeDePreparation = typeDePreparation;
this.lieu = lieu;
this.nbrQuestionFacile = nbrQuestionFacile;
this.nbrQuestionMoyen = nbrQuestionMoyen;
this.nbrQuestionDifficle = nbrQuestionDifficle;
}
public ResponsableTechnique getRésponsableTechnique() {
return responsableTechnique;
}
public void setRésponsableTechnique(ResponsableTechnique
résponsableTechnique) {
this.responsableTechnique = résponsableTechnique;
}
public String getTypeDePreparation() {
return typeDePreparation;
}
public void setTypeDePreparation(String typeDePreparation) {
this.typeDePreparation = typeDePreparation;
}
public String getLieu() {
return lieu;
}
public void setLieu(String lieu) {
this.lieu = lieu;
}
public int getNbrQuestionFacile() {
return nbrQuestionFacile;
}
public void setNbrQuestionFacile(int nbrQuestionFacile) {
this.nbrQuestionFacile = nbrQuestionFacile;
}
public int getNbrQuestionMoyen() {
return nbrQuestionMoyen;
}
public void setNbrQuestionMoyen(int nbrQuestionMoyen) {
this.nbrQuestionMoyen = nbrQuestionMoyen;
}
public int getNbrQuestionDifficle() {
return nbrQuestionDifficle;
}
public void setNbrQuestionDifficle(int nbrQuestionDifficle) {
this.nbrQuestionDifficle = nbrQuestionDifficle;
}
public Collection<Resultat> getResultats() {
return resultats;
}
public void setRésultats(Collection<Resultat> resultats) {
this.resultats = resultats;
}
}
}
When you get Test and access Test.questions later, after leaving the transaction, you will get a lazy initialization exception when the Test entity is detached and questions has not been initialized/fetched yet. You can either do a specific fetch, or depending on your configuration, you can call Test.getQuestions().size() before you exit the transaction.
References: How to solve lazy initialization exception using JPA and Hibernate as provider
LazyInitializationException in JPA and Hibernate
Hibernate LazyInitializationException using Spring CrudRepository
I have a Canteen class and a Course class (and a BaseEntity). The Canteen class has a set of courses. A course is unique if the composition of name, dateOfServing and the canteen id is unique. I tried to write a test case which should throw an exception if a non-unique course is added to a canteen. But the test doesn't throw any exception at all. Which leads me to believe that I'm doing me Canteen and Course class wrong. The test in question is addDuplicatedCourseToCanteenTest. Anyone got a clue about what I'm doing wrong?
I'm new to TDD as well so any critique in that area is very welcome as well.
BaseEntity.java
#MappedSuperclass
public class BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
long id;
private Date createdAt;
private Date updatedAt;
// TODO: http://stackoverflow.com/a/11174297/672009
// Using the above we wouldn't have to created a CommentRepository
// Is that a good idea?
/**
* http://www.devsniper.com/base-entity-class-in-jpa/
*/
/**
* Sets createdAt before insert
*/
#PrePersist
public void setCreationDate() {
this.setCreatedAt(new Date());
}
/**
* Sets updatedAt before update
*/
#PreUpdate
public void setChangeDate() {
this.setUpdatedAt(new Date());
}
public Date getCreatedAt() {
return createdAt;
}
protected void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
protected void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id ^ (id >>> 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;
BaseEntity other = (BaseEntity) obj;
if (id != other.id)
return false;
return true;
}
}
Canteen.java
#Entity
public class Canteen extends BaseEntity {
private String name;
// TODO: https://schuchert.wikispaces.com/JPA+Tutorial+1+-+Embedded+Entity
// http://docs.oracle.com/javaee/6/api/javax/xml/registry/infomodel/PostalAddress.html
//private Address address;
//private PostalAddress postalAddress;
/**
* In honor of KISS I simply use a simple string address as a holder for the restaurants address.
* The idea is that the string will contain an address which will be valid according to google maps.
* Same goes for openingHours, phoneNumber and homepage... KISS wise.
*/
private String address;
private String openingHours; // A string which will be presented within a pre tag
// Eg. <pre>Mandag - Torsdag 10-22
// Fredag - Lørdag 10-24
// Søndag 11-20</pre>
private String contact;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<Course> courses = new HashSet<>();
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 getOpeningHours() {
return openingHours;
}
public void setOpeningHours(String openingHours) {
this.openingHours = openingHours;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public Set<Course> getCourses() {
return courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
public boolean addCourse(Course course)
{
return getCourses().add(course);
}
#Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Canteen other = (Canteen) obj;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
Course.java
#Entity
public class Course extends BaseEntity {
private String name;
private Date dateOfServing;
#ManyToOne
private Canteen canteen;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDateOfServing() {
return dateOfServing;
}
public void setDateOfServing(Date dateOfServing) {
this.dateOfServing = dateOfServing;
}
public Canteen getCanteen() {
return canteen;
}
public void setCanteen(Canteen canteen) {
this.canteen = canteen;
}
#Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((canteen == null) ? 0 : canteen.hashCode());
result = prime * result
+ ((dateOfServing == null) ? 0 : dateOfServing.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Course other = (Course) obj;
if (canteen == null) {
if (other.canteen != null)
return false;
} else if (!canteen.equals(other.canteen))
return false;
if (dateOfServing == null) {
if (other.dateOfServing != null)
return false;
} else if (!dateOfServing.equals(other.dateOfServing))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
CanteenHasCoursesTest.java
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = PersistenceConfig.class)
public class CanteenHasCoursesTest {
#Autowired
private CanteenRepository canteenRepository;
private String canteenName;
private String courseName;
private Canteen canteen;
private Course course;
#Before
public void setUp() {
// Generate unique random name
canteenName = UUID.randomUUID().toString();
// Generate unique random name
courseName = UUID.randomUUID().toString();
// Create new canteen
canteen = new Canteen();
canteen.setName(canteenName);
// Create new course
course = new Course();
course.setName(courseName);
}
#Test
public void addCourseToCanteenTest() {
// Add course
canteen.addCourse(course);
// Save canteen
canteenRepository.save(canteen);
// Find it again
Canteen c = canteenRepository.findOne(canteen.getId());
// Confirm attributes are as expected
assertNotNull(c);
Set<Course> courses = c.getCourses();
Iterator<Course> it = courses.iterator();
assertTrue(it.hasNext());
Course course = it.next();
assertEquals(courseName, course.getName());
}
// TODO: expect some data violation exception
// #Test(expected = IndexOutOfBoundsException.class)
#Test
public void addDuplicatedCourseToCanteenTest() {
// Add course
canteen.addCourse(course);
// Add it again
canteen.addCourse(course);
// Save canteen
canteenRepository.save(canteen);
}
#After
public void tearDown() {
canteenRepository = null;
canteenName = null;
courseName = null;
canteen = null;
course = null;
}
}
My entity class is
#Entity
public class Student_enroll implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private int level_num;
private int term;
private String student_session;
private HashMap<String,Integer>mark_value;
#OneToOne
private Student student;
public String getStudent_session() {
return student_session;
}
public void setStudent_session(String student_session) {
this.student_session = student_session;
}
public int getLevel_num() {
return level_num;
}
public void setLevel_num(int level_num) {
this.level_num = level_num;
}
public int getTerm() {
return term;
}
public void setTerm(int term) {
this.term = term;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public HashMap<String, Integer> getMark_value() {
return mark_value;
}
public void setMark_value(HashMap<String, Integer> mark_value) {
this.mark_value = mark_value;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Student_enroll)) {
return false;
}
Student_enroll other = (Student_enroll) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.domain.Student_enroll[ id=" + id + " ]";
}
}
and my controller function is
#RequestMapping(value="/add_mark",method = RequestMethod.POST)
public void add_mark(HttpServletRequest req){
HashMap<String,Integer>map=new HashMap<String,Integer>();
int level=Integer.parseInt(req.getParameter("level"));
int term=Integer.parseInt(req.getParameter("term"));
Student_enroll enroll=student_service.get_student_enroll(level, term);
List<Course>list_course=course_service.list_course(level, term);
Iterator<Course>itr=list_course.iterator();
while(itr.hasNext()){
enroll.put(itr.next().getCourse_Code(),75);
}
enroll.setMark_value(map); // Set hashmap
student_service.update_student_enroll(enroll);
}
I want to set the HashMap by using setHashmap() and want to persist the entity in database.is it an appropriate way cause when I want to persist it other attribute of entity is persisted but the hashmap attribute contains a BLOB object.
How to persist a hashmap of primitive type?
JPA supports Map persistencse using #MapKey, #MapKeyJoinColumn ... annotations
Refer to following article for details:
http://en.wikibooks.org/wiki/Java_Persistence/Relationships#Maps