Entity's equals() don't work properly in HashSet - java

Could you give me an idea mhy equals() doesn't work properly in POJO, when its entity is added to HashSet? I checked and hascode() works correctly because returns the same hashcode for entities with equal fields. But nevertheless equal objects are added in HashSet. Please take a look at the code below:
#Entity
#Table(name = "account")
public class Account {
private int accountID;
private String accountNumber;
private float amount;
private String currency;
private Client clientID;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "account_id")
public int getAccountID() {
return accountID;
}
public void setAccountID(int accountID) {
this.accountID = accountID;
}
#Column(name = "account_number")
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
#Column(name = "amount")
public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
#Column(name = "currency")
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "client_id")
public Client getClientID() {
return clientID;
}
public void setClientID(Client clientID) {
this.clientID = clientID;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Account)) return false;
Account account = (Account) o;
if (Float.compare(account.amount, amount) != 0) return false;
if (!accountNumber.equals(account.accountNumber)) return false;
if (!clientID.equals(account.clientID)) return false;
if (!currency.equals(account.currency)) return false;
return true;
}
#Override
public int hashCode() {
int result = accountNumber.hashCode();
result = 31 * result + (amount != +0.0f ? Float.floatToIntBits(amount) : 0);
result = 31 * result + currency.hashCode();
result = 31 * result + clientID.hashCode();
return result;
}
}

result = 31 * result + clientID.hashCode();
I think with this line of code the hashCode of the two objects are not the same.Try to remove this line and test

thank you for pieces of advice but I realised what my mistake was. I didn't clarify that the application is used Hibernate for saving objects to DB. Objects are added in HashSet during particular Hibernate session. When I add an equal object to the one which is already in DB it happens in new Hibernate session with new empty HashSet.

Related

Hibernate and ManyToMany + #OrderColumn returns 42075 Null records

when I use #OrderColumn annotation, Hibernate returns collection with 42075 [Null] records, but without #OrderColumn everything works perfectly why? I want to use field "OrderNumber" to have always ordered entity by this field. The type of this "OrderNumber" on PostgreSQL side is "serial" with auto increasing count.
DocTestEntity:
#Entity
#Table(name = "`Document`")
public class DocTestEntity implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "`Document_ID`")
private Integer id;
#ManyToMany
#JoinTable(name = "`DocumentEmployee`",
joinColumns = #JoinColumn(name = "`Document_ID`"),
inverseJoinColumns = #JoinColumn(name = "`Employee_ID`"))
#OrderColumn(name ="`OrderNumber`", updatable = false, insertable = false)
private List<EmployeeTestEntity> employeeEntityList;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<EmployeeTestEntity> getEmployeeEntityList() {
return employeeEntityList;
}
public void setEmployeeEntityList(List<EmployeeTestEntity> employeeEntityList) {
this.employeeEntityList = employeeEntityList;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DocTestEntity docEntity = (DocTestEntity) o;
return Objects.equals(id, docEntity.id);
}
#Override
public int hashCode() {
return Objects.hash(id);
}
#Override
public String toString() {
return "DocTestEntity{" +
"id=" + id +
'}';
}
}
EmployeeTestEntity:
#Entity
#Table(name = "`Employee`")
public class EmployeeTestEntity implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "`Employee_ID`")
private Integer id;
#Column(name = "`Employee_name`")
private String name;
#Column(name = "`Employee_surname`")
private String surname;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String employeeName) {
this.name = employeeName;
}
public String getSurname() {
return surname;
}
public void setSurname(String employeeSurname) {
this.surname = employeeSurname;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EmployeeTestEntity that = (EmployeeTestEntity) o;
return Objects.equals(id, that.id);
}
#Override
public int hashCode() {
return Objects.hash(id);
}
#Override
public String toString() {
return "EmployeeTestEntity{" +
"id=" + id +
'}';
}
}
And Test DAO:
#Stateless
public class DocTestDAO {
#PersistenceContext
private EntityManager em;
public DocTestEntity selectDocumentByID(Integer id) {
var result = em.createQuery("SELECT DISTINCT a from DocTestEntity a " +
" WHERE a.id = :id ", DocTestEntity.class)
.setParameter("id", id)
.getResultStream()
.map(Optional::ofNullable)
.findFirst()
.flatMap(Function.identity())
.orElse(null);
System.out.println("List records count is: " + result.getEmployeeEntityList().size());
return result;
}
}
You don't need the OrderNumber column to be autoincremented, the hibernate can manage the order column itself depending on the order of the items in the collection employeeEntityList.
You should make the OrderNumber to be insertable and updatable (true by default):
#OrderColumn(name = "OrderNumber")
I would recommend cleaning up the code, removing these apostrophes from the column names
"`DocumentEmployee`" should be "DocumentEmployee". You mentioned that everything could work without #OrderColumn, so I suppose apostrophes don't affect the functionality but look weird.
Please let me know if this still doesn't work after mentioned updates.

Java Hot swap failed and schema change is not implemented

I work on a Java Spring boot app where I get the error of Hot-swap failed and schema change is not implemented and the operation is not supported by the VM. Afterward, the table is truncated and have no data at all.
I have 2 models provided below,
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name")
#NotNull
#NotEmpty
private String name;
#Column(name = "countryName")
#NotNull
#NotEmpty
private String countryName;
#Column(name = "currencyName")
#NotNull
#NotEmpty
private String currencyName;
/*
* total steps is for the keepign the history of the user movement
* */
#Column(name = "totalSteps")
#Min(value = 0L, message = "The value must be positive")
private int totalSteps;
/*
* current steps is for providing the user reward. We will need to set
* it to zero after processing the user payment
* */
#Column(name = "currentSteps")
#Min(value = 0L, message = "The value must be positive")
private int currentSteps;
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private List<RewardList> rewardLists = new ArrayList<>();
public User() {
}
public User(#NotNull #NotEmpty String name, #NotNull #NotEmpty String countryName) {
this.name = name;
this.countryName = countryName;
}
public User(#NotNull #NotEmpty String name, #NotNull #NotEmpty String countryName, #Min(value = 0L, message = "The value must be positive") int totalSteps) {
this.name = name;
this.countryName = countryName;
this.totalSteps = totalSteps;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountryName() {
return countryName;
}
public String getCurrencyName() {
return currencyName;
}
public void setCurrencyName(String currencyName) {
this.currencyName = currencyName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public int getTotalSteps() {
return totalSteps;
}
public void setTotalSteps(int totalSteps) {
this.totalSteps = totalSteps;
}
public int getCurrentSteps() {
return currentSteps;
}
public void setCurrentSteps(int currentSteps) {
this.currentSteps = currentSteps;
}
public List<RewardList> getRewardLists() {
return rewardLists;
}
public void setRewardLists(RewardList rl) {
this.rewardLists.add(rl);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User)) return false;
User user = (User) o;
return getTotalSteps() == user.getTotalSteps() &&
getCurrentSteps() == user.getCurrentSteps() &&
getId().equals(user.getId()) &&
getName().equals(user.getName()) &&
getCountryName().equals(user.getCountryName()) &&
getRewardLists().equals(user.getRewardLists());
}
#Override
public int hashCode() {
return Objects.hash(getId(), getName(), getCountryName(), getTotalSteps(), getCurrentSteps(), getRewardLists());
}
#Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", countryName='" + countryName + '\'' +
", totalSteps=" + totalSteps +
", currentSteps=" + currentSteps +
'}';
}
}
#Entity
public class RewardList {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "reward")
#Min(value = 0L, message = "The value must be positive")
private double reward;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id", nullable = false)
private User user;
public RewardList() {
}
public RewardList(User user) {
this.user = user;
}
public RewardList(#Min(value = 0L, message = "The value must be positive") double reward) {
this.reward = reward;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public double getReward() {
return reward;
}
public void setReward(double reward) {
this.reward = reward;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof RewardList)) return false;
RewardList list = (RewardList) o;
return Double.compare(list.getReward(), getReward()) == 0 &&
getId().equals(list.getId()) &&
getUser().equals(list.getUser());
}
#Override
public int hashCode() {
return Objects.hash(getId(), getReward(), getUser());
}
#Override
public String toString() {
return "RewardList{" +
"id=" + id +
", reward=" + reward +
", user=" + user +
'}';
}
}
The end-point where I have this issue provided below,
// $ curl -X PUT http://localhost:8080/api/v1/users/calculateReward?userId=1 | jq
#PutMapping("/calculateReward")
public ResponseEntity<Object> calculateReward(#RequestParam("userId") Long userId) {
Optional<User> optional = userService.findById(userId);
if (!optional.isPresent()) {
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
User user = optional.get();
double reward = user.getCurrentSteps() * Parameters.REWARD_PER_STEPS_EUR;
RewardList list = new RewardList();
list.setUser(user);
list.setReward(reward);
rewardListService.save(list);
user.setCurrentSteps(0);
user.setRewardLists(list);
userService.save(user);
JSONObject json = new JSONObject();
double convertionRateToEuro = currencyMap.get(user.getCurrencyName());
double rewardConverted = reward * convertionRateToEuro;
json.put("name", user.getName());
json.put("currency", user.getCurrencyName());
json.put("reward", rewardConverted);
return ResponseEntity.status(HttpStatus.CREATED).body(json);
}
Does anyone know what is going on and can provide a solution?
Thank you.
I find the reason and below I provide a solution. We will need to save the models based on the hierarchy. HotSwap doesn't support adding methods or hierarchy changes as indicated by the error messages. It's the limitation of Java HotSwap, not IntelliJ IDEA. The proper way of code sequence will be,
User user = optional.get();
RewardList list = new RewardList();
list.setUser(user);
list.setReward(reward);
user.setCurrentSteps(0);
user.setRewardLists(list);
// first save the User
userService.save(user);
// Then, save the RewardList as it has one to many relations
rewardListService.save(list);

InvalidDataAccessApiUsageException: Parameter value element did not match expected type

I'm trying to execute an IN query with by using Spring Data. My model looks like this:
#Entity
#Table(name = "customer", schema = "public", catalog = "postgres")
public class CustomerEntity {
private int id;
private String name;
private int balance;
private String bankId;
#Id
#Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "balance")
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
#Basic
#Column(name = "bank_id")
public String getBankId() {
return bankId;
}
public void setBankId(String bankId) {
this.bankId = bankId;
}
And my repository interface looks like this:
#Repository
public interface TransactionsRepository extends JpaRepository<TransactionsEntity, Long> {
List<TransactionsEntity> findByCustomerIdIn(List<CustomerEntity> customerEntities);
}
The problem is that when I try to execute this code
List<TransactionsEntity> transactionsEntitiesList = transactionsRepository.findByCustomerIdIn(customerEntitiesList);
I get this exception:
Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value element [org.example.domain.admin.CustomerEntity#6a1a2a4] did not match expected type [java.lang.String (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value element [org.example.domain.admin.CustomerEntity#6a1a2a4] did not match expected type [java.lang.String (n/a)]
Update: TransactionsEntity.class:
#Entity
#Table(name = "transactions", schema = "public", catalog = "postgres")
public class TransactionsEntity {
private String id;
private String amount;
private String customerId;
#Id
#Column(name = "id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Basic
#Column(name = "amount")
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
#Basic
#Column(name = "customer_id")
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TransactionsEntity that = (TransactionsEntity) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (amount != null ? !amount.equals(that.amount) : that.amount != null) return false;
if (customerId != null ? !customerId.equals(that.customerId) : that.customerId != null) return false;
return true;
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (amount != null ? amount.hashCode() : 0);
result = 31 * result + (customerId != null ? customerId.hashCode() : 0);
return result;
}
}
As it says in the exception Spring expects a String because your customer_id in your TransactionEntity is a String, but you are inputting a CustomerEntity. Instead you should input a List<String> with the list of your customer ids.
Btw shouldn't your customer_id be an int assuming you set it to the id of your CustomerEntity?
Then you could do something like
List<Integer> customerIds = customerEntitiesList.stream().map(CustomerEntity::getId).collect(Collectors.toList());

Issues while trying to create a hibernate query that navigates through many-to-many associations with additional join table entity and composite key

I have three entities: Account, AccountAttribut and Attribut. Account and Attribut are associated via AccountAttribut in a many-to-many relationship like it is described here (1). AccountAttribut is a join table entity that holds an additional attribute.
I try to build a HQL string that delivers all Accounts with the "wert"-property "John" in AccountAttribut and the name-property "FirstName" in Attribut.
I dont find the right HQL string. Can you help me out?
(1): http://giannigar.wordpress.com/2009/09/04/mapping-a-many-to-many-join-table-with-extra-column-using-jpa/ "Mapping a many-to-many join table with extra column using JPA"
I tried this query:
List<Account> queried_accounts = HibernateUtils.queryList(
session.createQuery(""
+ "from Account as acc"
+ " full join acc.accountAttributes as accAtt"
+ " inner join accAtt.aa_pk.attribut as attr"
+ " where attr.name='FirstName' and accAtt.wert='John'")
);
and i get this error message:
ERROR: You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'full outer join account_attribut accountatt1_ on
account0_.account_id=accountatt' at line 1
UPDATE:
I changed the query to:
List<Account> queried_accounts = HibernateUtils.queryList(
session.createQuery(""
+ "from Account as acc"
+ " inner join acc.accountAttributes as accAtt"
+ " inner join accAtt.aa_pk.attribut as attr"
+ " where attr.name='FirstName' and accAtt.wert='John'")
);
This seems to work.
But now i got a new Problem: queried_accounts does not seem to be a List of Accounts. If i get an object out of queried_accounts and try to apply account methods on it, i get an Exception at runtime.
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to
com.computacenter.qct.pojos.Account
These are relevant code extracts:
Account:
#Entity
#Table(name = "account")
public class Account {
private Long accountId;
private List<AccountAttribut> accountAttributes = new LinkedList<AccountAttribut>();
private Person person;
private Zielsystem zielsystem;
public Account() {
}
#Id
#GeneratedValue
#Column(name = "account_id", nullable = false)
public Long getAccountId() {
return accountId;
}
public void setAccountId(Long accountId) {
this.accountId = accountId;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "aa_pk.account", cascade = {
CascadeType.PERSIST, CascadeType.MERGE })
#Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE,
org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
public List<AccountAttribut> getAccountAttributes() {
return accountAttributes;
}
public void setAccountAttributes(List<AccountAttribut> accountAttribute) {
this.accountAttributes = accountAttribute;
}
#ManyToOne
#JoinColumn(name = "person_id")
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
#ManyToOne
#JoinColumn(name="zielsystem_id")
public Zielsystem getZielsystem() {
return zielsystem;
}
public void setZielsystem(Zielsystem zielsystem) {
this.zielsystem = zielsystem;
}
}
AccountAttribut:
#Entity
#Table(name="account_attribut")
#AssociationOverrides({
#AssociationOverride(name="aa_pk.account", joinColumns = #JoinColumn(name="account_id")),
#AssociationOverride(name="aa_pk.attribut", joinColumns = #JoinColumn(name="attribut_id"))
})
public class AccountAttribut {}
private AccountAttributPk aa_pk = new AccountAttributPk();
#Column(name="wert")
private String wert;
#EmbeddedId
public AccountAttributPk getAa_pk() {
return aa_pk;
}
public void setAa_pk(AccountAttributPk aa_pk) {
this.aa_pk = aa_pk;
}
#Transient
public Account getAccount() {
return getAa_pk().getAccount();
}
public void setAccount(Account account) {
getAa_pk().setAccount(account);
}
#Transient
public Attribut getAttribut() {
return getAa_pk().getAttribut();
}
public void setAttribut(Attribut attribut) {
getAa_pk().setAttribut(attribut);
}
public String getWert() {
return wert;
}
public void setWert(String wert) {
this.wert = wert;
}
public boolean equals(Object o) {
if (this== o) return true;
if (o ==null|| getClass() != o.getClass()) return false;
AccountAttribut that = (AccountAttribut) o;
if (getAa_pk() !=null?!getAa_pk().equals(that.getAa_pk()) : that.getAa_pk() !=null) return false;
return true;
}
public int hashCode() {
return (getAa_pk() !=null? getAa_pk().hashCode() : 0);
}
}
AccountAttributPk:
public class AccountAttributPk implements Serializable {
private static final long serialVersionUID = -1551814445010872872L;
private Account account;
private Attribut attribut;
#ManyToOne
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
#ManyToOne
public Attribut getAttribut() {
return attribut;
}
public void setAttribut(Attribut attribut) {
this.attribut = attribut;
}
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
AccountAttributPk that = (AccountAttributPk) o;
if (account != null ? !account.equals(that.account) : that.account != null)
return false;
if (attribut != null ? !attribut.equals(that.attribut)
: that.attribut != null)
return false;
return true;
}
public int hashCode() {
int result;
result = (account != null ? account.hashCode() : 0);
result = 31 * result + (attribut != null ? attribut.hashCode() : 0);
return result;
}
}
Attribut
#Entity
#Table(name="Attribut")
public class Attribut {
private Long attributId;
private String name;
private List<PersonAttribut> personenAttribute = new LinkedList<PersonAttribut>();
private List<AccountAttribut> accountAttribute = new LinkedList<AccountAttribut>();
private List<BerechtigungsobjektAttribut> berechtigungsobjektAttribute = new LinkedList<BerechtigungsobjektAttribut>();
public Attribut() {}
public Attribut(String name) {
this.name = name;
}
#Id
#GenericGenerator(name="generator", strategy="increment")
#GeneratedValue(generator="generator")
#Column(name="attribut_id", nullable=false)
public Long getAttributId() {
return attributId;
}
public void setAttributId(Long attributId) {
this.attributId = attributId;
}
#Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pa_pk.attribut", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
#Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
public List<PersonAttribut> getPersonenAttribute() {
return personenAttribute;
}
public void setPersonenAttribute(List<PersonAttribut> personenAttribute) {
this.personenAttribute = personenAttribute;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "aa_pk.attribut", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
#Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
public List<AccountAttribut> getAccountAttribute() {
return accountAttribute;
}
public void setAccountAttribute(List<AccountAttribut> accountAttribute) {
this.accountAttribute = accountAttribute;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "ba_pk.attribut", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
#Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
public List<BerechtigungsobjektAttribut> getBerechtigungsobjektAttribute() {
return berechtigungsobjektAttribute;
}
public void setBerechtigungsobjektAttribute(
List<BerechtigungsobjektAttribut> berechtigungsobjektAttribute) {
this.berechtigungsobjektAttribute = berechtigungsobjektAttribute;
}
#Override
public String toString() {
return name;
}
#Override
public boolean equals(Object other) {
if (other == null)
return false;
if (this == other)
return true;
if (this.getClass() != other.getClass())
return false;
final Attribut otherAccount = (Attribut) other;
return EqualsUtils.nullSafeEquals(this.getName(), otherAccount.getName());
}
#Override
public int hashCode() {
final int PRIME = 42;
return this.name.hashCode() * PRIME;
}
}

Mapping a table with a composite primary key

I have the following Entity in hibernate, using JPA annotations
#Entity
#IdClass(PurchaseCounter.PurchaseCounterPK.class)
#Table(name = "customer_purchases_counter")
public class PurchaseCounter {
public static class PurchaseCounterPK implements Serializable {
Integer customerId;
Integer purchaseId;
public PurchaseCounterPK(Integer customerId, Integer purchaseId) {
this.customerId = customerId;
this.purchaseId = purchaseId;
}
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
public Integer getPurchaseId() {
return purchaseId;
}
public void setPurchaseId(Integer purchaseId) {
this.purchaseId = purchaseId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PurchaseCounterPK that = (PurchaseCounterPK) o;
if (customerId != null ? !customerId.equals(that.customerId) : that.customerId != null) return false;
if (purchaseId != null ? !purchaseId.equals(that.purchaseId) : that.purchaseId != null) return false;
return true;
}
#Override
public int hashCode() {
int result = customerId != null ? customerId.hashCode() : 0;
result = 31 * result + (purchaseId != null ? purchaseId.hashCode() : 0);
return result;
}
}
Integer customerId;
Integer purchaseId;
Integer count = 0;
#Id
#Column(name = "customer_id")
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
#Id
#Column(name = "purchase_id")
public Integer getPurchaseId() {
return purchaseId;
}
public void setPurchaseId(Integer purchaseId) {
this.purchaseId = purchaseId;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
}
when I do a query using Criteria and using purchaseId and customerId as Restriction.eq filters, that's the query that gets generated:
select this_.customerId as customerId137_0_, this_.purchaseId as purchaseId137_0_, this_.count as count137_0_ from customer_purchases_counter this_ where this_.purchaseId=? and this_.customerId=?
that of course is wrong because the fields customerId and purchaseId are not renamed to their names that I specified using #Column????
Mapping seems to be correct. This is likely occurrence of HHH-4256 (Hibernate does not honor #Column(name=...) annotation with IdClass) . If so, then updating to the newer version of Hibernate offers solution.
Also according bug report using #Column annotation in IdClass is workaround.
I'm not sure if I understand correctly, but the #Column specified simply which column to map to your java data.
So you should not apply the #Column annotation to your getters, but rather to your variable declarations themselves.
#ID
#Column (name="customer_Id")
Integer customerId;
#ID
#Column (name="purchase_Id")
Integer purchaseId;

Categories