Unable to retrieve data from MySQL using Spring boot JPA - java

I am getting a java.lang.NullPointerException error at the line where the program begins to retrieve data from the database, specifically starting with the code recordDB.setAccountName(billing.getAccountId().getAccountName());. The entity tables are joined together and at first I thought that it can't retrieve data from other other tables but I tried to run with just recordDB.setAmount(billing.getAmount()); Can someone explain what I missed or is there something wrong with the logic?
Component
#Component
public class FileProcessor {
#Autowired
private BillingRepository billingRepository;
public FileProcessor() {
}
public List<Record> retrieveRecordfromDB(List<Request> requests) throws BarsException{
List<Record> records = new ArrayList<>();
if (!requests.isEmpty()) {
for (Request request : requests) {
Billing billing = billingRepository
.findByBillingCycleAndStartDateAndEndDate(
request.getBillingCycle()
, request.getStartDate()
, request.getEndDate());
if (billing == null) {
throw new BarsException(BarsException.NO_RECORDS_TO_WRITE);
}
Record recordDB = new Record();
recordDB.setBillingCycle(request.getBillingCycle());
recordDB.setStartDate(request.getStartDate());
recordDB.setEndDate(request.getStartDate());
recordDB.setAccountName(billing.getAccountId().getAccountName());
recordDB.setFirstName(billing.getAccountId().getCustomerId().getFirstName());
recordDB.setLastName(billing.getAccountId().getCustomerId().getLastName());
recordDB.setAmount(billing.getAmount());
records.add(recordDB);
}
}
return records;
}
}
Account Entity
#Entity
public class Account {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "account_id")
private int accountId;
private String accountName;
private LocalDateTime dateCreated;
private String isActive;
private String lastEdited;
public Account() {
}
public int getAccountId() {
return accountId;
}
public void setAccountId(int accountId) {
this.accountId = accountId;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public LocalDateTime getDateCreated() {
return dateCreated;
}
public void setDateCreated(LocalDateTime dateCreated) {
this.dateCreated = dateCreated;
}
public String getIsActive() {
return isActive;
}
public void setIsActive(String isActive) {
this.isActive = isActive;
}
public String getLastEdited() {
return lastEdited;
}
public void setLastEdited(String lastEdited) {
this.lastEdited = lastEdited;
}
public Customer getCustomerId() {
return customerId;
}
public void setCustomerId(Customer customerId) {
this.customerId = customerId;
}
public Set<Billing> getBilling() {
return billing;
}
public void setBilling(Set<Billing> billing) {
this.billing = billing;
}
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "customer_id")
private Customer customerId;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "account_id")
private Set<Billing> billing;
}
Billing Entity
#Entity
public class Billing {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "billing_id")
private int billingId;
//private int billingId;
private int billingCycle;
private String billingMonth;
private Double amount;
private LocalDate startDate;
private LocalDate endDate;
private String lastEdited;
//private Account accountId;
public Billing() {
}
public int getBillingId() {
return billingId;
}
public void setBillingId(int billingId) {
this.billingId = billingId;
}
public int getBillingCycle() {
return billingCycle;
}
public void setBillingCycle(int billingCycle) {
this.billingCycle = billingCycle;
}
public String getBillingMonth() {
return billingMonth;
}
public void setBillingMonth(String billingMonth) {
this.billingMonth = billingMonth;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
public LocalDate getStartDate() {
return startDate;
}
public void setStartDate(LocalDate startDate) {
this.startDate = startDate;
}
public LocalDate getEndDate() {
return endDate;
}
public void setEndDate(LocalDate endDate) {
this.endDate = endDate;
}
public String getLastEdited() {
return lastEdited;
}
public void setLastEdited(String lastEdited) {
this.lastEdited = lastEdited;
}
public Account getAccountId() {
return accountId;
}
public void setAccountId(Account accountId) {
this.accountId = accountId;
}
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "account_id")
private Account accountId;
}
Customer Entity
#Entity
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "customer_id")
private int customerId;
private String firstName;
private String lastName;
private String address;
private String status;
private LocalDateTime dateCreated;
private String lastEdited;
public Customer() {
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public LocalDateTime getDateCreated() {
return dateCreated;
}
public void setDateCreated(LocalDateTime dateCreated) {
this.dateCreated = dateCreated;
}
public String getLastEdited() {
return lastEdited;
}
public void setLastEdited(String lastEdited) {
this.lastEdited = lastEdited;
}
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "customer_id")
private Set<Account> account;
}
Repository
#Repository
public interface BillingRepository extends JpaRepository<Billing, Integer> {
public Billing findByBillingCycleAndStartDateAndEndDate (int billingCycle, LocalDate startDate, LocalDate endDate);
}

Your naming is unintuitive, which hinders people unfamiliar with the code:
recordDB implies that it is the Database for records. Instead, it is a record that is to be saved in the DB. Naming it "RecordToSave" or similar is much better, since it gets the intention across.
getAccountId() implies that the id of an account is returned (an int or long) NOT that the account itself is returned. You should rename it to getAccount()
About the issue:
What you are using as a bidirectional ManyToOne <-> OneToMany relationship.
One side should be the owning side of the relationship. Here the #JoinColumn should be stated. The receiving end should have a MappedBy Property.
See this guide for more information: https://thorben-janssen.com/hibernate-tips-map-bidirectional-many-one-association/
It should solve the issue, since only the data retrieval for connected tables does not seem to work, hence fixing the references should fix the issue.
Your billing.getAmount() does refer to data written in the billing object/table, and is not from another table like billing.getAccountId().getAccountName() which gets data from the account table connected to the billings table.
Last, but not least:
Think about your cascading strategy. The way it currently works, deleting a billing will delete the account of that billing, which deletes all references made there and so on since you currently use Cascade.All for ALL entries. This is bad.
Here is a guide for cascading: https://howtodoinjava.com/hibernate/hibernate-jpa-cascade-types/

Are you sure the field names in the Billing class exactly match the database column names? I see you set the column name to "billing_id" explicitly for the id field, but not for any other fields. My guess is that the fields in that class are all null since there are no corresponding database columns (debug to confirm).

Related

How to delete many-to-many relationship?

I have a many-to-many relationship (Car & driver) How, when deleting a Driver, delete a link in the driver_car table and delete cars that were bound to this driver, and vice versa, when deleting a car, simply delete a car and links in the driver_car table that are not associated with this by car?
My BaseEntity:
#MappedSuperclass
public abstract class BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Temporal(TemporalType.TIMESTAMP)
private Date created;
#Temporal(TemporalType.TIMESTAMP)
private Date updated;
private Boolean visible;
#Column(name = "image_url")
private String imageUrl;
public BaseEntity() {
this.created = new Date();
this.updated = new Date();
this.visible = true;
}
#PreUpdate
public void preUpdate() {
this.updated = new Date();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
public Boolean getVisible() {
return visible;
}
public void setVisible(Boolean visible) {
this.visible = visible;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
My Driver:
#Entity
#Table(name = "drivers")
public class Driver extends BaseEntity {
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
private String notes;
private double balance;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(
name = "driver_car",
joinColumns = #JoinColumn(name = "driver_id"),
inverseJoinColumns = #JoinColumn(name = "car_id"))
private Set<Car> cars;
public Driver() {
super();
this.cars = new HashSet<>();
}
public Set<Car> getCars() {
return cars;
}
public void setCars(Set<Car> cars) {
this.cars = cars;
}
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 String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
My Car:
#Entity
#Transactional
public class Car extends BaseEntity {
#Column(name = "cars_name")
private String carName;
private String color;
#Column(name = "engine_of_capacity")
private double engineCapacity;
#Column(name = "years_of_issue")
private Integer yearsOfIssue;
#Column(name = "car_number")
private String carNumber;
#ManyToMany(mappedBy = "cars", cascade = CascadeType.ALL)
private Set<Driver> drivers;
public Car() {
super();
drivers = new HashSet<>();
}
public Set<Driver> getDrivers() {
return drivers;
}
public void setDrivers(Set<Driver> drivers) {
this.drivers = drivers;
}
public String getCarNumber() {
return carNumber;
}
public void setCarNumber(String carNumber) {
this.carNumber = carNumber;
}
public String getCarName() {
return carName;
}
public void setCarName(String carName) {
this.carName = carName;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public double getEngineCapacity() {
return engineCapacity;
}
public void setEngineCapacity(double engineCapacity) {
this.engineCapacity = engineCapacity;
}
public Integer getYearsOfIssue() {
return yearsOfIssue;
}
public void setYearsOfIssue(Integer yearsOfIssue) {
this.yearsOfIssue = yearsOfIssue;
}
}
Delete Car:
#Override
public void delete(Long id) {
entityManager.createQuery("delete from Car s where s.id = :id")
.setParameter("id", id)
.executeUpdate();
}
Delete Driver:
#Override
public void delete(Long id) {
entityManager.createQuery("delete from Driver d where d.id = :id")
.setParameter("id", id)
.executeUpdate();
}
One should be very cautious about using CascadeType.ALL for #ManyToMany associations, since this might yield surprising results as described e.g. here:
https://thorben-janssen.com/best-practices-for-many-to-many-associations-with-hibernate-and-jpa/#The_CascadeType_you_should_avoid_at_all_costs
In the best case, it only creates performance issues, but in the worst case, it might also remove more records than you intended.
So a better way would be e.g. to have a dedicated service logic which specifies exactly which entities are to be deleted and which of course also takes care of synchronizing both sides of the association.
This way there can also be a simple check whether a previously associated Car has no more associated Drivers after one was deleted, so that the "orphan" Car can then be deleted as well.

How to write hibernate insert query if entity name is saved in a variable

In my application I came to a situation where i need to save some data to an entity but the entity name is unknown, and is saved in a variable and entity field and its value are in a list.So i need to pick the entity name from variable and its field and data from list.
Variable is xEntity.
public void saveData(String xEntity,List<Attribute> attributeList) {
// hibernate insert query
}
Some of the entity class are shown below which may come as the xEntity,and attributeList in function saveData().
#Entity
#Table(name = "person")
public class Person implements Serializable {
#Id
#GeneratedValue
#Column(name = "id")
private Integer id;
#Column(name = "emp_id")
private String empId;
#Column(name = "name")
private String name;
#Column(name="dob")
private Date dob;
#Column(name="active")
private Boolean active;
#Column(name="created_on")
private Timestamp createdOn;
public Person() {
}
public Person(Integer id, String empId, String name, Date dob, Boolean active, Timestamp createdOn) {
this.id = id;
this.empId = empId;
this.name = name;
this.dob = dob;
this.active = active;
this.createdOn = createdOn;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public Timestamp getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Timestamp createdOn) {
this.createdOn = createdOn;
}
}
#Entity
#Table(name = "person_address")
public class PersonAddress implements Serializable {
#Id
#GeneratedValue
#Column(name = "id")
private Integer id;
#Column(name = "emp_id")
private String empId;
#Column(name = "house_name")
private String houseName;
#Column(name="post_office")
private String postOffice;
#Column(name="district")
private String district;
#Column(name="state")
private String state;
#Column(name="active")
private Boolean active;
#Column(name="created_on")
private Timestamp createdOn;
public PersonAddress() {
}
public PersonAddress(Integer id, String empId, String houseName, String postOffice, String district, String state, Boolean active, Timestamp createdOn) {
this.id = id;
this.empId = empId;
this.houseName = houseName;
this.postOffice = postOffice;
this.district = district;
this.state = state;
this.active = active;
this.createdOn = createdOn;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getHouseName() {
return houseName;
}
public void setHouseName(String houseName) {
this.houseName = houseName;
}
public String getPostOffice() {
return postOffice;
}
public void setPostOffice(String postOffice) {
this.postOffice = postOffice;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public void setState(String state) {
this.state = state;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public Timestamp getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Timestamp createdOn) {
this.createdOn = createdOn;
}
}
#Entity
#Table(name = "person_qualification")
public class PersonQualification implements Serializable {
#Id
#GeneratedValue
#Column(name = "id")
private Integer id;
#Column(name = "emp_id")
private String empId;
#Column(name = "degree")
private String degree;
#Column(name="grade")
private String grade;
#Column(name="active")
private Boolean active;
#Column(name="created_on")
private Timestamp createdOn;
public PersonQualification() {
}
public PersonQualification(Integer id, String empId, String degree, String grade, Boolean active, Timestamp createdOn) {
this.id = id;
this.empId = empId;
this.degree = degree;
this.grade = grade;
this.active = active;
this.createdOn = createdOn;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getDegree() {
return degree;
}
public void setDegree(String degree) {
this.degree = degree;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public Timestamp getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Timestamp createdOn) {
this.createdOn = createdOn;
}
}
Below are some of the values that may come to attributeList each time.
attributeList = [{"fieldName":"empId","value":"EMP_123"},{"fieldName":"name","value":"Basil"},{"fieldName":"dob","value":"26-11-90"}]
attributeList = [{"fieldName":"empId","value":"EMP_123"},{"fieldName":"houseName","value":"Ellikkal"},{"fieldName":"postOffice","value":"Chengara"},{"fieldName":"district","value":"Alappy"},{"fieldName":"state","value":"Kerala"}]
attributeList = [{"fieldName":"empId","value":"EMP_123"},{"fieldName":"degree","value":"B.Tech"},{"fieldName":"grade","value":"First class"}]
Date value come as string date which should be formatted to type Date.Below is the Attribute class.
public class Attribute implements Serializable {
private String fieldName;
private String value;
public Attribute() {
super();
// TODO Auto-generated constructor stub
}
public Attribute(String fieldName, String value) {
this.fieldName = fieldName;
this.value = value;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Now can i use hibernate query to save data to each entity?If anyone know please help me.
Though I don't know why you want to do this but if you have no other choice then you have to use reflection here.
First create instance using your class name. It should be full class name. Also your classes should have default constructor.
Class<?> clazz = Class.forName(className);
Constructor<?> ctor = clazz.getConstructor();
Object object = ctor.newInstance();
Now use reflection to set the values of fields. Lets assume your field name is stored in fieldName and value is stored in fieldValue
declaredField = object.getClass().getDeclaredField(fieldName);
declaredField.setAccessible(true);
declaredField.set(object, fieldValue);
For the cases where you need to convert the type from String to Date etc. You have to get field type and convert accordingly. Field type can be found out by:
declaredField.getFieldType();
Now save this object using hibernate.
sessionFactory.getCurrentSession().save(object);
I'm afraid HQL doesn't support inserting per query but you can use reflection to build your entities or create a native query.

Hibernate Automatically load relationships

I have the following Entity classes UserEntity and TicketEntity. A User has many tickets and many tickets can belong to a user. My question is, is there a way to automatically load all the tickets belonging to a pertaining user by using Hibernate or do I have to manually load all the entity relationships from the DB? I think the .load() does this but I'm not quite sure. In my case could I do something like
userEntity.load()
Any help is appreciated, thanks
UserEntity.java
package com.issuetracking.domain;
/**
*/
import java.util.List;
import javax.persistence.*;
#Entity
#Table(name="user")
public class UserEntity {
#Id
#Column(name="user_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="firstname")
private String firstname;
#Column(name="lastname")
private String lastname;
#Column(name="username")
private String username;
#Column(name="email")
private String email;
#Column(name="password")
private String password;
#Transient
private String confirmpassword;
#Column(name="verified")
private boolean verified;
#Column(name="role_id")
private int role_id;
#OneToMany(fetch = FetchType.LAZY)
private List<TicketEntity> tickets;
//Getters/Setters
public List<TicketEntity> getTickets() {
return tickets;
}
public void setTickets(List<TicketEntity> tickets) {
this.tickets = tickets;
}
public int getRole_id() {
return role_id;
}
public void setRole_id(int role_id) {
this.role_id = role_id;
}
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 String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmpassword() {
return confirmpassword;
}
public void setConfirmpassword(String confirmpassword) {
this.confirmpassword = confirmpassword;
}
public boolean isVerified() {
return verified;
}
public void setVerified(boolean verified) {
this.verified = verified;
}
}
TicketEntity.java
package com.issuetracking.domain;
import java.util.Date;
import javax.persistence.*;
#Entity
#Table(name="ticket")
public class TicketEntity {
#Id
#Column(name="ticket_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="title")
private String title;
#Column(name="description")
private String description;
#Column(name="date_created")
#Temporal( TemporalType.TIMESTAMP )
private Date date_created;
#Column(name="status_id")
private int status_id;
//private TicketStatus status;
#Column(name="urgency_id")
private int urgency_id;
#ManyToOne
#JoinColumn(name="user_id", insertable=false, updatable=false)
private UserEntity belongs_to;
#ManyToOne
#JoinColumn(name="user_id", insertable=false, updatable=false)
private UserEntity assigned_to;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getDate_created() {
return date_created;
}
public void setDate_created(Date date_created) {
this.date_created = date_created;
}
public int getStatus_id() {
return status_id;
}
public void setStatus_id(int status_id) {
this.status_id = status_id;
}
public int getUrgency_id() {
return urgency_id;
}
public void setUrgency_id(int urgency_id) {
this.urgency_id = urgency_id;
}
public UserEntity getBelongs_to() {
return belongs_to;
}
public void setBelongs_to(UserEntity belongs_to) {
this.belongs_to = belongs_to;
}
public UserEntity getAssigned_to() {
return assigned_to;
}
public void setAssigned_to(UserEntity assigned_to) {
this.assigned_to = assigned_to;
}
}
A User has many tickets and many tickets can belong to a user.
In this case relationship should be ManyToMany
My question is, is there a way to automatically load all the tickets belonging to a pertaining user
Use EAGER FetchType instead of LAZY , Like
#OneToMany(fetch = FetchType.EAGER)
private List<TicketEntity> tickets;

hibernate gives two rows the same instead of two distinct rows

I have a user dao
#Entity
#Table(name="EBIGUSERTIM")
public class EbigUser {
private String id;
private Integer source;
private String entryscheme;
private String fullName;
private String email;
private Long flags;
private String status;
private String createdBy;
private Date createdStamp;
private String modifiedBy;
private Date modifiedStamp;
#Id
#Column(name="ID")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Id
#Column(name="SOURCE")
public Integer getSource() {
return source;
}
public void setSource(Integer source) {
this.source = source;
}
#Column(name="ENTRYSCHEME")
public String getEntryscheme() {
return entryscheme;
}
public void setEntryscheme(String entryscheme) {
this.entryscheme = entryscheme;
}
#Column(name="FULLNAME")
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
#Column(name="EMAIL")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name="FLAGS")
public Long getFlags() {
return flags;
}
public void setFlags(Long flags) {
this.flags = flags;
}
#Column(name="STATUS")
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Column(name="CREATEDBY")
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
#Column(name="CREATEDSTAMP")
public Date getCreatedStamp() {
return createdStamp;
}
public void setCreatedStamp(Date createdStamp) {
this.createdStamp = createdStamp;
}
#Column(name="MODIFIEDBY")
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
#Column(name="MODIFIEDSTAMP")
public Date getModifiedStamp() {
return modifiedStamp;
}
public void setModifiedStamp(Date modifiedStamp) {
this.modifiedStamp = modifiedStamp;
}
i am selecting 2 rows out of the db. The sql works
select * from ebigusertim where id='blah'
It returns 2 distinct rows. When i query the data using hibernate, it appears that the object memory is not being allocated for each entry in the list. Thus, i get 2 entries in the list with the same object.
Criteria userCriteria = session.createCriteria(EbigUser.class);
userCriteria.add(Restrictions.eq("id", id));
userlist = userCriteria.list();
Why are you defining two id columns(both id and source are mapped with annotation #Id)?
#Id
#Column(name="ID")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Id
#Column(name="SOURCE")
public Integer getSource() {
return source;
}
Please remove one if it is by mistake. If both together make composite key, map them accordingly e.g.
#Embeddable
public class UserPK implements Serializable {
#Column(name = "ID", nullable = false)
private String id;
#Column(name = "SOURCE", nullable = false)
private Integer source;
.....
.....
}
Use this new class in you original class as Id as below:
#EmbeddedId
private UserPK userPK;
Hope this helps.

How to join Maps

How to join newMap detals in custMap.
Map<String, Customer> custMap= new HashMap<String,Customer>();
Map<String, DoCustomer> newMap= new HashMap<String,DoCustomer>();
for (Map.Entry<String, DoCustomer> cust: newMap.entrySet()) {
custMap.put(cust.getKey(),cust.getValue());
}
public class DoCustomer {
private Long id;
private String custName;
private String description;
private String status;
private List<DoCustomerBranch> doCustomerBranch=new ArrayList<DoCustomerBranch>
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
getter/setters of doCustomerBranch
}
#Entity
#Table(name = "CUSTOMER")
public class Customer implements Serializable{
private static final long serialVersionUID = 1L;
private Long id;
private String custName;
private String description;
private String createdBy;
private Date createdOn;
private String updatedBy;
private Date updatedOn;
private Set<CustomerBranch> customerBranch=new HashSet<CustomerBranch>
#Id
#GeneratedValue(generator = "CUSTOMER_SEQ")
#SequenceGenerator(name = "CUSTOMER_SEQ", sequenceName = "CUSTOMERN_SEQ", allocationSize = 1)
#Column(name = "ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "CUST_NAME",nullable=false)
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
#Column(name = "DESCRIPTION")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "CREATED_BY", length = 50)
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CREATED_ON")
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
#Column(name = "UPDATED_BY", length = 50)
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "UPDATED_ON")
public Date getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(Date updatedOn) {
this.updatedOn = updatedOn;
}
#OneToMany(cascade = { CascadeType.PERSIST, CascadeType.REMOVE }, fetch = FetchType.LAZY, mappedBy = "customer")
public Set<CustomerBranch> getCustomerBranch() {
return customerBranch;
}
public void setCustomerBranch(Set<CustomerBranch> customerBranch) {
this.customerBranch = customerBranch;
}
}
CustomerBranch
#Entity
#Table(name = "CUSTOMER_BRANCH")
public class CustomerBranch implements Serializable{
#Id
#GeneratedValue(generator = "CUSTOMER_BRANCH_SEQ")
#SequenceGenerator(name = "CUSTOMER_BRANCH_SEQ", sequenceName = "CUSTOMER_BRANCH_SEQ", allocationSize = 1)
#Column(name = "ID")
private Long id;
private String branchName;
private String branchAddress;
private Customer customer;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "BRANCH_NAME",nullable=false)
public String getBranchName() {
return branchName;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "MOBEE_CUSTOMER")
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
The problem with your code is that you want to put a DoCustomer in a Customer container. It only works if DoCustomer is a subclass of Customer.
Edit 1: You could use BeanUtils to convert a DoCustomer into a Customer. Here is a good tutorial.
Do you mean:
custMap.putAll(newMap)
As everyone else has pointed out, we need to know what DoCustomer is to be able to help.
But, from what you have given us, I'd suggest casting each DoCustomer to a Customer or, more correctly, making a new Customer from the fields of each DoCustomer.
Something like:
custMap.put(cust.getKey(), new Customer(cust.getValue().getId(), cust.getValue().getCustName(), and so on..));
inside your for loop.
I can see the customer class defined you have provided doesn't have a constructor, so naturally you would have to add one to it

Categories