hibernate gives two rows the same instead of two distinct rows - java

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.

Related

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.

Java Arraylist change one attribute value in all objects at the same time

I have a model with this attribute
public class Audit extends BaseModel implements Comparable {
#Column
#PrimaryKey
#SerializedName("audit_id")
private int id;
#Column
#SerializedName("address_line_1")
private String addressLine1;
#Column
#SerializedName("address_line_2")
private String addressLine2;
#Column
#SerializedName("city_name")
private String city;
#Column
#SerializedName("zip_code")
private String zipcode;
#Column
#SerializedName("company_id")
private int companyId;
#Column
#SerializedName("company_name")
private String companyName;
#Column
#SerializedName("loc_name")
private String location;
#Column
#SerializedName("inspection_date_time")
private OffsetDateTime inspectionTime;
#Column
#SerializedName("inspection_number")
private String inspectionNumber;
#Column(defaultValue = "0")
private int auditStatus;
#Column(defaultValue = "0")
private int userId;
public int getId() {
return id;
}
public String getAddressLine1() {
return addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public String getCity() {
return city;
}
public String getZipcode() {
return zipcode;
}
public int getCompanyId() {
return companyId;
}
public String getCompanyName() {
return companyName;
}
public String getLocation() {
return location;
}
public OffsetDateTime getInspectionTime() {
return inspectionTime;
}
public String getInspectionNumber() {
return inspectionNumber;
}
public void setId(int id) {
this.id = id;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public void setCity(String city) {
this.city = city;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public void setCompanyId(int companyId) {
this.companyId = companyId;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public void setLocation(String location) {
this.location = location;
}
public void setInspectionTime(OffsetDateTime inspectionTime) {
this.inspectionTime = inspectionTime;
}
public void setInspectionNumber(String inspectionNumber) {
this.inspectionNumber = inspectionNumber;
}
#Override
public int compareTo(#NonNull Object audits) {
int result = -1;
if (audits instanceof Audit) {
Audit audit = (Audit) audits;
if (this.getInspectionTime().isEqual(audit.getInspectionTime())) {
result = 0;
} else if
(this.getInspectionTime().isAfter(audit.getInspectionTime())) {
result = 1;
}
}
return result;
}
public int getAuditStatus() {
return auditStatus;
}
public void setAuditStatus(int auditStatus) {
this.auditStatus = auditStatus;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
In here I get all values to Arraylist using this model
List<Audit> auditList
My list is "auditList", It contains Audit objects, In this auditList I want to chnge one attribute
for ex: I want to change userId value to "3" in all objects, How can I do it once, Is there any solution please Help Me
Using Java 8 Stream :
auditList.stream().forEach(elt -> elt.setUserId(3));
It corresponds to :
for (Audit aud : auditList) {
aud.setUserId(3);
}
You will need to iterate through all elements and update
for (Audit aud : auditList) {
aud.setUserId(3);
}
If you want it on one line then
for (Audit aud : auditList) aud.setUserId(3);

EclipseLink ADD CONSTRAINT Exception

I would like to use create-or-extend-tables but eclipselink gives below error after tables were created. I am using Eclipselink 2.5.2 and db is MS Sql 2014
Exception [EclipseLink-4002] (Eclipse Persistence Services -
2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException Internal
Exception: com.microsoft.sqlserver.jdbc.SQLServerException:
'announcementCOMPANY_ID' object already exists. Error Code: 2714 Call:
ALTER TABLE announcement ADD CONSTRAINT announcementCOMPANY_ID FOREIGN
KEY (COMPANY_ID) REFERENCES company (ID) Query:
DataModifyQuery(sql="ALTER TABLE announcement ADD CONSTRAINT
announcementCOMPANY_ID FOREIGN KEY (COMPANY_ID) REFERENCES company
(ID)")
Persistance.java
persistenceMap.put("javax.persistence.jdbc.driver", ConfigParams
.getInstance().getValue(ConfigConstants.JDBC_DRIVER));
persistenceMap.put("javax.persistence.jdbc.user", ConfigParams
.getInstance().getValue(ConfigConstants.JDBC_USER));
persistenceMap.put("javax.persistence.jdbc.password", ConfigParams
.getInstance().getValue(ConfigConstants.JDBC_PASSWORD));
persistenceMap.put("javax.persistence.jdbc.url", ConfigParams
.getInstance().getValue(ConfigConstants.JDBC_URL));
persistenceMap.put("eclipselink.logging.logger",
Log4jSessionLog.class.getName());
// persistenceMap.put("eclipselink.logging.file",
// Log4jSessionLog.class.getName());
persistenceMap
.put("eclipselink.ddl-generation.output-mode", "database");
persistenceMap.put("eclipselink.weaving.internal", "false");
persistenceMap.put("eclipselink.logging.level", ConfigParams
.getInstance().getValue(ConfigConstants.JDBC_LOGGING_LEVEL));
persistenceMap.put("eclipselink.ddl-generation",
"create-or-extend-tables");
Announcement.java
#Entity
#Table(name="announcement")
public class Announcement {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "annId")
private int id;
#Column(nullable =false, length = 250, name="annName")
private String name;
#Column(length = 250)
private String mainTitle;
#Column(nullable=false, length = 250)
private String subTitle;
#Lob
private String content;
#Column(nullable = false)
private Date startDate;
#Transient
private java.util.Date startDateUtil;
#Column(nullable = false)
private Date endDate;
#Transient
private java.util.Date endDateUtil;
#Lob
private String imgUrl;
#Column(nullable = false)
private boolean isActive;
#Column(nullable = false)
private boolean isDeleted;
#Transient
private BtcResponse status;
private Type type;
#ManyToMany
#JoinTable(name="announcementLogs")
private List<Log> logAList = new ArrayList<Log>();
private Company company;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMainTitle() {
return mainTitle;
}
public void setMainTitle(String mainTitle) {
this.mainTitle = mainTitle;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public java.util.Date getStartDateUtil() {
return startDateUtil;
}
public void setStartDateUtil(java.util.Date startDateUtil) {
this.startDateUtil = startDateUtil;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public java.util.Date getEndDateUtil() {
return endDateUtil;
}
public void setEndDateUtil(java.util.Date endDateUtil) {
this.endDateUtil = endDateUtil;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean isActive) {
this.isActive = isActive;
}
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean isDeleted) {
this.isDeleted = isDeleted;
}
public BtcResponse getStatus() {
return status;
}
public void setStatus(BtcResponse status) {
this.status = status;
}
public List<Log> getLogAList() {
return logAList;
}
public void setLogAList(List<Log> logAList) {
this.logAList = logAList;
}
#ManyToOne
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public Announcement() {
super();
}
public Announcement(BtcResponse status) {
super();
this.status = status;
}
public Announcement(java.util.Date startDateUtil,
java.util.Date endDateUtil, String imgUrl, boolean isActive) {
super();
this.startDateUtil = startDateUtil;
this.endDateUtil = endDateUtil;
this.imgUrl = imgUrl;
this.isActive = isActive;
}
#ManyToOne
#JoinColumn(name = "id")
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
}
Company.java
#Entity
#Table(name="company")
public class Company {
#Id
#Column(nullable = false)
private int id;
#Column(length = 100, nullable = false, name="companyName")
private String name;
private List<Banner> bannerList = new ArrayList<Banner>();
private List<Announcement> announcementList = new ArrayList<Announcement>();
private List<PriceList> priceList = new ArrayList<PriceList>();
#OneToMany(mappedBy="company")
public List<Announcement> getAnnouncementList() {
return announcementList;
}
public void setAnnouncementList(List<Announcement> announcementList) {
this.announcementList = announcementList;
}
#Transient
private BtcResponse status;
public int getId() {
return id;
}
public Company(int id, String name) {
super();
this.id = id;
this.name = name;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(mappedBy="company")
public List<Banner> getBannerList() {
return bannerList;
}
public void setBannerList(List<Banner> bannerList) {
this.bannerList = bannerList;
}
public BtcResponse getStatus() {
return status;
}
public void setStatus(BtcResponse status) {
this.status = status;
}
public Company() {
super();
}
public Company(BtcResponse status) {
super();
this.status = status;
}
#OneToMany(mappedBy="company")
public List<PriceList> getPriceList() {
return priceList;
}
public void setPriceList(List<PriceList> priceList) {
this.priceList = priceList;
}
}

hibernate many to one annotations - mapping exception

I have to tables book and borrow and I want to have in my Borrow class method to get Book. I have something like this:
#Entity
#Table(name="borrow")
public class Borrow {
#Id
#Column(name="ID")
#GeneratedValue
private Long id;
#Column(name="book_id")
private long bookId;
#Column(name="user_id")
private long userId;
#Column(name="borrow_date")
private Date borrowDate;
#Column(name="return_date")
private Date returnDate;
private Book book;
public long getBookId() {
return bookId;
}
public void setBookId(long bookId) {
this.bookId = bookId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id", nullable = false)
#ForeignKey(name = "id")
public Book getBook() {
return this.book;
}
public void setBook(Book book) {
this.book = book;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public Date getBorrowDate() {
return borrowDate;
}
public void setBorrowDate(Date borrowDate) {
this.borrowDate = borrowDate;
}
public Date getReturnDate() {
return returnDate;
}
public void setReturnDate(Date returnDate) {
this.returnDate = returnDate;
}
}
In table book I have id field and I want to join by it. Like book.id = borrow.book_id. I get execption:
Could not determine type for: Book, at table: borrow, for columns: [org.hibernate.mapping.Column(book)]
Book class:
#Entity
#Table(name="book")
public class Book {
#Id
#Column(name="ID")
#GeneratedValue
private Long id;
#Column(name="title")
private String title;
#Column(name="author")
private String author;
#Column(name="isbn")
private String isbn;
#Column(name="year")
private String year;
#Column(name="publisher")
private String publisher;
#Column(name="book_url")
private String bookUrl;
#Column(name="review_url")
private String reviewUrl;
#Column(name="status_id")
private int status;
#Column(name="accepted")
private boolean accepted;
#Column(name="in_library")
private boolean inLibrary;
#Column(name="user_id")
private long userId;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public boolean isAccepted() {
return accepted;
}
public void setAccepted(boolean accepted) {
this.accepted = accepted;
}
public boolean isInLibrary() {
return inLibrary;
}
public void setInLibrary(boolean inLibrary) {
this.inLibrary = inLibrary;
}
public Book(long l, String string) {
this.title = string;
this.id = l;
}
public Book() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getBookUrl() {
return bookUrl;
}
public void setBookUrl(String bookUrl) {
this.bookUrl = bookUrl;
}
public String getReviewUrl() {
return reviewUrl;
}
public void setReviewUrl(String reviewUrl) {
this.reviewUrl = reviewUrl;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
The issue is that you're mixing field and property access. Your #Id annotation is on a field, so that's where hibernate is looking for book's annotation. From 2.2.2.2. Access type:
The placement of annotations within a class hierarchy has to be
consistent (either field or on property) to be able to determine the
default access type. It is recommended to stick to one single
annotation placement strategy throughout your whole application.
So either keep your annotations consistent (recommended), or use the methods described in the rest of that section to override the access type for book (e.g. by using the #Access annotation)

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