Lombok Maven different of Lombok in Eclipse or STS - java

I have a delta between compile by Maven and compile by Eclipse. By Maven is OK but not by Eclipse.
In compile by Eclipse, it misses the #ConstructorProperties({ "id", "profile" }) annotation on the constructor that has both parameters.
My java file:
#Data
#AllArgsConstructor
public class Author {
private String id;
private String profile;
}
Full class by Maven (OK):
import java.beans.ConstructorProperties;
public class Author {
private String id;
private String profile;
public void setId(String id) {
this.id = id;
}
public void setProfile(String profile) {
this.profile = profile;
}
#Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof Author)) {
return false;
}
final Author other = (Author) o;
if (!other.canEqual(this)) {
return false;
}
final Object this$id = getId();
final Object other$id = other.getId();
if (this$id == null ? other$id != null : !this$id.equals(other$id)) {
return false;
}
final Object this$profile = getProfile();
final Object other$profile = other.getProfile();
return this$profile == null ? other$profile == null : this$profile.equals(other$profile);
}
protected boolean canEqual(Object other) {
return other instanceof Author;
}
#Override
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $id = getId();
result = result * 59 + ($id == null ? 43 : $id.hashCode());
final Object $profile = getProfile();
result = result * 59 + ($profile == null ? 43 : $profile.hashCode());
return result;
}
#Override
public String toString() {
return "Author(id=" + getId() + ", profile=" + getProfile() + ")";
}
#ConstructorProperties({ "id", "profile" })
public Author(String id, String profile) {
this.id = id;
this.profile = profile;
}
public String getId() {
return id;
}
public String getProfile() {
return profile;
}
}
Full class by Eclipse:
public class Author {
private String id;
private String profile;
public String getId() {
return id;
}
public String getProfile() {
return profile;
}
public void setId(String id) {
this.id = id;
}
public void setProfile(String profile) {
this.profile = profile;
}
#Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof Author)) {
return false;
}
final Author other = (Author) o;
if (!other.canEqual(this)) {
return false;
}
final Object this$id = getId();
final Object other$id = other.getId();
if (this$id == null ? other$id != null : !this$id.equals(other$id)) {
return false;
}
final Object this$profile = getProfile();
final Object other$profile = other.getProfile();
return this$profile == null ? other$profile == null : this$profile.equals(other$profile);
}
protected boolean canEqual(Object other) {
return other instanceof Author;
}
#Override
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $id = getId();
result = result * 59 + ($id == null ? 43 : $id.hashCode());
final Object $profile = getProfile();
result = result * 59 + ($profile == null ? 43 : $profile.hashCode());
return result;
}
#Override
public String toString() {
return "Author(id=" + getId() + ", profile=" + getProfile() + ")";
}
public Author(String id, String profile) {
this.id = id;
this.profile = profile;
}
}

#tobias_k find solution:
Eclipse need same version of Lombok installed that Maven project use.

Related

How to use #lombok.Builder.Default with java records

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");
}
}

How to create object in object Spring JPA (Jhipster)

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<>();

Spring RequestBody Mapping maps all attributes to null values

i have the following RESTfull method :
#RequestMapping(value = "/budgetLines",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public void create(#RequestBody BudgetLine budgetLine) {
System.out.println("Before Persisting in the repository " + budgetLine);
budgetLineRepository.save(budgetLine);
}
I'am consuming this method inside a web application, i checked using the network analysis tool (in the web developper tool of chrome) that the object sended is valid (all attribute except the id were set with a valid value), but then the object passed to the repository contains only null attributes.
here is an example body :
{
"Name":"testLabel",
"Label":"testName",
"AnnualBudget":9000
}
the class BudgetLine is defined as follows:
#Entity
#Table(name = "T_BUDGETLINE")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class BudgetLine implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "label")
private String Label;
#Column(name = "name")
private String Name;
#Column(name = "annual_budget", precision=10, scale=2)
private BigDecimal AnnualBudget;
#OneToMany(mappedBy = "budgetLine")
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Report> reportss = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLabel() {
return Label;
}
public void setLabel(String Label) {
this.Label = Label;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public BigDecimal getAnnualBudget() {
return AnnualBudget;
}
public void setAnnualBudget(BigDecimal AnnualBudget) {
this.AnnualBudget = AnnualBudget;
}
public Set<Report> getReportss() {
return reportss;
}
public void setReportss(Set<Report> Reports) {
this.reportss = Reports;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BudgetLine budgetLine = (BudgetLine) o;
if (id != null ? !id.equals(budgetLine.id) : budgetLine.id != null) return false;
return true;
}
#Override
public int hashCode() {
return (int) (id ^ (id >>> 32));
}
#Override
public String toString() {
return "BudgetLine{" +
"id=" + id +
", Label='" + Label + "'" +
", Name='" + Name + "'" +
", AnnualBudget='" + AnnualBudget + "'" +
'}';
}
public BudgetLine() {
}
}
Try with first letter in lowercase for parameters
{
"name":"testLabel",
"label":"testName",
"annualBudget":9000
}
Spring relies heavily on standard Java naming conventions, so I suggest you also follow them. In your example, you should name your class fields with lowercased first letter.

Canteen with uniqe courses

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;
}
}

Java hashmap mapping in database

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

Categories

Resources