equals and hashCode of these entities (Spring MVC + Hibernate) - java

Someone can please suggest me how I can do equals and hashCode methods of these entities?
This is a many-to-many relationship between a Gara (Contest) and Agenzia (Agency):
One contest has many Agency, one Agency can be in more Contest.
I tried some implementations but or I get Stackoverflow error, or,
when I'm updating a Gara (Contest), I can't update the set of Agenzie (Agencies) because i get this error:
org.springframework.dao.DuplicateKeyException: a different object with
the same identifier value was already associated with the session:
[com.myApp.model.GaraAgenzia#com.mmyApp.model.GaraAgenziaId#49f];
nested exception is org.hibernate.NonUniqueObjectException: a
different object with the same identifier value was already associated
with the session:
[com.myApp.model.GaraAgenzia#com.myApp.model.GaraAgenziaId#49f]
when i try to do an update.
thanks
Gare.java:
#Entity
#Table(name = "gare")
public class Gara extends BaseEntity implements Serializable {
private static final long serialVersionUID = 6395640401966812691L;
/*
* inizializzo logger
*/
static Logger logger = LoggerFactory.getLogger(Gara.class);
/*
* molti a molti gara-agenzia
*
* EAGER altrimenti da errore: could not initialize proxy - no Session
*/
#OneToMany(fetch = FetchType.EAGER, mappedBy = "pk.gara", cascade=CascadeType.ALL, orphanRemoval=true)
private Set<GaraAgenzia> garaAgenzie = new HashSet<GaraAgenzia>(0);
/*
* molti a molti gara-servizi
*
* EAGER altrimenti da errore: could not initialize proxy - no Session
*/
#OneToMany(fetch = FetchType.EAGER, mappedBy = "pk.gara", cascade=CascadeType.ALL, orphanRemoval=true)
private Set<GaraServizio> garaServizi = new HashSet<GaraServizio>(0);
/*
*
* colonna TITOLO
*
*/
#NotNull(message = "Il campo TITOLO è obbligatorio")
#NotEmpty(message = "Il campo TITOLO è obbligatorio")
#Size(min = 0, max = 255, message = "Lunghezza massima campo TITOLO: 255 caratteri")
#Column(name = "TITOLO", length = 255)
private String titolo;
/*
*
* colonna OBIETTIVO
*
*/
#NotNull(message = "Il campo OBIETTIVO è obbligatorio")
#Min(value = 1, message = "Il campo OBIETTIVO deve essere maggiore di ZERO")
#Column(name = "OBIETTIVO")
private int obiettivo = 0;
/*
*
* colonna BONUS
*
*/
#NotNull(message = "Il campo BONUS è obbligatorio")
#Min(value = 1, message = "Il campo BONUS deve essere maggiore di UNO")
#Column(name = "BONUS")
private float bonus = 0f;
#Column(name = "data_iniziale", nullable = false)
private Date dataIniziale;
#Column(name = "data_finale", nullable = false)
private Date dataFinale;
public Set<GaraAgenzia> getGaraAgenzie() {
return garaAgenzie;
}
public void setGaraAgenzie(Set<GaraAgenzia> garaAgenzie) {
this.garaAgenzie.clear();
this.garaAgenzie = garaAgenzie;
}
public Set<GaraServizio> getGaraServizi() {
return garaServizi;
}
public void setGaraServizi(Set<GaraServizio> garaServizi) {
this.garaServizi.clear();
this.garaServizi = garaServizi;
}
public void GaraServizio(GaraServizio gara_servizio) {
garaServizi.add(gara_servizio);
gara_servizio.setGara(this);
}
public void removeGaraServizio(GaraServizio gara_servizio) {
garaServizi.remove(gara_servizio);
gara_servizio.setGara(null);
}
public void GaraAgenzia(GaraAgenzia gara_agenzia) {
garaAgenzie.add(gara_agenzia);
gara_agenzia.setGara(this);
}
public void removeGaraAgenzia(GaraAgenzia gara_agenzia) {
garaAgenzie.remove(gara_agenzia);
gara_agenzia.setGara(null);
}
public String getTitolo() {
return titolo;
}
public void setTitolo(String titolo) {
this.titolo = titolo;
}
public int getObiettivo() {
return obiettivo;
}
public void setObiettivo(int obiettivo) {
this.obiettivo = obiettivo;
}
public float getBonus() {
return bonus;
}
public void setBonus(float bonus) {
this.bonus = bonus;
}
public Date getDataIniziale() {
return dataIniziale;
}
public void setDataIniziale(Date dataIniziale) {
this.dataIniziale = dataIniziale;
}
public Date getDataFinale() {
return dataFinale;
}
public void setDataFinale(Date dataFinale) {
this.dataFinale = dataFinale;
}
#Override
public String toString() {
return "Gara [garaAgenzie=" + garaAgenzie + ", garaServizi="
+ garaServizi + ", titolo=" + titolo + ", obiettivo="
+ obiettivo + ", bonus=" + bonus + ", dataIniziale="
+ dataIniziale + ", dataFinale=" + dataFinale + "]";
}
#Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + Float.floatToIntBits(bonus);
result = prime * result
+ ((dataFinale == null) ? 0 : dataFinale.hashCode());
result = prime * result
+ ((dataIniziale == null) ? 0 : dataIniziale.hashCode());
result = prime * result + obiettivo;
result = prime * result + ((titolo == null) ? 0 : titolo.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;
Gara other = (Gara) obj;
if (Float.floatToIntBits(bonus) != Float.floatToIntBits(other.bonus))
return false;
if (dataFinale == null) {
if (other.dataFinale != null)
return false;
} else if (!dataFinale.equals(other.dataFinale))
return false;
if (dataIniziale == null) {
if (other.dataIniziale != null)
return false;
} else if (!dataIniziale.equals(other.dataIniziale))
return false;
if (obiettivo != other.obiettivo)
return false;
if (titolo == null) {
if (other.titolo != null)
return false;
} else if (!titolo.equals(other.titolo))
return false;
return true;
}
}
GaraAgenzia.java:
#Entity
#Table(name = "gare_agenzie")
#AssociationOverrides({
#AssociationOverride(name = "pk.gara",
joinColumns = #JoinColumn(name = "gara_id")),
#AssociationOverride(name = "pk.agenzia",
joinColumns = #JoinColumn(name = "agenzia_id")) })
public class GaraAgenzia implements Serializable {
private static final long serialVersionUID = 3865586469933888797L;
/*
* inizializzo logger
*/
static Logger logger = LoggerFactory.getLogger(GaraAgenzia.class);
/*
*
* numero contratti:
*
*
*/
private int numeroContratti = 0;
private GaraAgenziaId pk = new GaraAgenziaId();
#EmbeddedId
public GaraAgenziaId getPk() {
return pk;
}
public void setPk(GaraAgenziaId pk) {
this.pk = pk;
}
#Transient
public Gara getGara() {
return getPk().getGara();
}
public void setGara(Gara gara) {
getPk().setGara(gara);
}
#Transient
public Agenzia getAgenzia() {
return getPk().getAgenzia();
}
public void setAgenzia(Agenzia agenzia) {
getPk().setAgenzia(agenzia);
}
#Column(name = "numero_contratti")
public int getNumeroContratti() {
return numeroContratti;
}
public void setNumeroContratti(int numeroContratti) {
this.numeroContratti = numeroContratti;
}
public boolean equals(Object other) {
if (this == other) return true;
if ( !(other instanceof GaraAgenzia) ) return false;
final GaraAgenzia gara_agenzia = (GaraAgenzia) other;
if ( !gara_agenzia.getGara().equals( getGara() ) ) return false;
if ( !gara_agenzia.getAgenzia().equals( getAgenzia() ) ) return false;
return true;
}
public int hashCode() {
int result;
result = getGara().hashCode();
result = 29 * result + getAgenzia().hashCode();
return result;
}
}
GaraAgenziaId.java:
#Embeddable
public class GaraAgenziaId implements Serializable {
private static final long serialVersionUID = 4934033367128755763L;
/*
* inizializzo logger
*/
static Logger logger = LoggerFactory.getLogger(GaraAgenziaId.class);
private Gara gara;
private Agenzia agenzia;
#ManyToOne
public Gara getGara() {
return gara;
}
public void setGara(Gara gara) {
this.gara = gara;
}
#ManyToOne
public Agenzia getAgenzia() {
return agenzia;
}
public void setAgenzia(Agenzia agenzia) {
this.agenzia = agenzia;
}
/*
* override del metodo di uguaglianza
*/
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null)
return false;
if (o instanceof GaraAgenzia) {
final GaraAgenzia other = (GaraAgenzia) o;
return (Objects.equal(getGara().getId(), other.getGara().getId())) && (Objects.equal(getAgenzia().getId(), other.getAgenzia().getId()));
}
return false;
}
/*
* override del metodo creazione hashcode
*/
#Override
public int hashCode() {
return Objects.hashCode(getGara().getId(), getAgenzia().getId());
}
/*
public boolean equals(Object other) {
if (this == other) return true;
if ( !(other instanceof GaraAgenziaId) ) return false;
final GaraAgenziaId gara_agenzia = (GaraAgenziaId) other;
if ( !gara_agenzia.getGara().equals( getGara() ) ) return false;
if ( !gara_agenzia.getAgenzia().equals( getAgenzia() ) ) return false;
return true;
}
public int hashCode() {
int result;
result = getGara().hashCode();
result = 29 * result + getAgenzia().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;
GaraAgenziaId other = (GaraAgenziaId) obj;
if (gara == null) {
if (other.gara != null)
return false;
} else if (!gara.equals(other.gara))
return false;
if (agenzia == null) {
if (other.agenzia != null)
return false;
} else if (!agenzia.equals(other.agenzia))
return false;
return true;
}
*/
}
Edit 1:
If i clear the set of Agencies (and Services) before
set again it:
garaToUpdate.getGaraAgenzie().clear();
garaToUpdate.getGaraServizi().clear();
getCurrentSession().flush();
garaToUpdate.setGaraAgenzie(gara.getGaraAgenzie());
garaToUpdate.setGaraServizi(gara.getGaraServizi());
getCurrentSession().update(garaToUpdate);
i get this error:
A collection with cascade="all-delete-orphan" was no longer
referenced by the owning entity instance:
Edit 2:
As suggested by #JamesB, i added the toString method to GaraAgenzia and GaraAgenziaId. Here the result BEFORE update the Gara record:
this is the record taken from db just before update it
INFO : com.machinet.model.GaraAgenziaId - garaToUpdate.GaraAgenzie
(before update): [GaraAgenzia [numeroContratti=0, pk=GaraAgenziaId
[Gara=Gara [titolo=gara title, obiettivo=999, bonus=100.00,
dataIniziale=2014-07-31, dataFinale=2014-07-31], agenzia=Agenzia(id=1,
nome='Agency 1 ltd', ragione sociale=Agency 1 ltd srl)]]]
this is the edited record that will be set in db:
INFO : com.machinet.model.GaraAgenziaId - editedGara.GaraAgenzie
(before update): [GaraAgenzia [numeroContratti=0, pk=GaraAgenziaId
[Gara=Gara [titolo=gara title, obiettivo=999, bonus=100.00,
dataIniziale=2014-07-31, dataFinale=2014-07-31], agenzia=Agenzia(id=1,
nome='Agency 1 ltd', ragione sociale=Agency 1 ltd srl]]]

These seem to work well. I post hoping someone will find it useful:
GaraAgenzia class:
public boolean equals(Object o) {
if (this== o) return true;
if (o ==null|| getClass() != o.getClass()) return false;
GaraAgenzia that = (GaraAgenzia) o;
if (getPk() !=null?!getPk().equals(that.getPk()) : that.getPk() !=null) return false;
return true;
}
public int hashCode() {
return (getPk() !=null? getPk().hashCode() : 0);
}
GaraAgenziaId class:
public boolean equals(Object o) {
if (this== o) return true;
if (o ==null|| getClass() != o.getClass()) return false;
GaraAgenziaId that = (GaraAgenziaId) o;
if (gara !=null?!gara.equals(that.gara) : that.gara !=null) return false;
if (agenzia !=null?!agenzia.equals(that.agenzia) : that.agenzia !=null)
return false;
return true;
}
public int hashCode() {
int result;
result = (agenzia !=null? agenzia.hashCode() : 0);
result =31* result + (gara !=null? gara.hashCode() : 0);
return result;
}

It is not an exactly answer, but may help someone in a similar problem. I made a abstract class that is extended by all the entities. This way I don't need to implement these methods in all entities.
public abstract class GenericEntity implements Serializable{
protected static final long serialVersionUID = 1L;
abstract public Serializable getId();
#Override
public int hashCode()
{
return (getId() == null) ? System.identityHashCode(this) : getId().hashCode();
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (this.getClass() != obj.getClass())
return false;
if (org.hibernate.Hibernate.getClass(this) != org.hibernate.Hibernate.getClass(obj))
return false;
GenericEntity other = (GenericEntity) obj;
if (getId() == null || other.getId() == null)
return false;
return getId().equals(other.getId());
}
}
I think in your case you could put it in your BaseEntity.

Related

No property timestamp found for type int! Traversed path: ScoreCard.score

While trying to run the spring boot application, I am getting the below errors.
1:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userStatsController'
2:
Error creating bean with name 'scoreCardRepository': Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Failed to create query for method
public abstract java.util.List.microservices.book.gamification.repository.ScoreCardRepository.findByUserIdOrderByScoreTimestampDesc(java.lang.Long)!
No property timestamp found for type int! Traversed path:
ScoreCard.score.
I am using the H2 database.
ScoreCardRepository.java
public interface ScoreCardRepository extends CrudRepository<ScoreCard, Long> {
#Query("SELECT SUM(s.score) FROM microservices.book.gamification.domain.ScoreCard s WHERE s.userId = :userId GROUP BY s.userId")
int getTotalScoreForUser(#Param("userId") final Long userId);
#Query("SELECT NEW microservices.book.gamification.domain.LeaderBoard(s.userId, SUM(s.score))"
+ "FROM microservices.book.gamification.domain.ScoreCard s "
+ "GROUP BY s.userId ORDER BY SUM(s.score) DESC")
List<LeaderBoardRow> findFirst10();
List<ScoreCard> findByUserIdOrderByScoreTimestampDesc(Long userId);
}
ScoreCard.java
#Entity
public class ScoreCard {
public static final int DEFAULT_SCORE = 20;
#Id
#GeneratedValue
#Column(name = "CARD_ID")
private Long cardId;
#Column(name = "USER_ID")
private Long userId;
#Column(name = "ATTEMPT_ID")
private Long attemptId;
#Column(name = "SCORE_TS")
private long scoreTimeStamp;
#Column(name = "SCORE")
private int score;
public ScoreCard() {
}
public ScoreCard(Long userId, Long attemptId) {
this.cardId = null;
this.userId = userId;
this.attemptId = attemptId;
this.scoreTimeStamp = System.currentTimeMillis();
this.score = DEFAULT_SCORE;
}
public Long getCardId() {
return cardId;
}
public Long getUserId() {
return userId;
}
public Long getAttemptId() {
return attemptId;
}
public long getScoreTimeStamp() {
return scoreTimeStamp;
}
public int getScore() {
return score;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((attemptId == null) ? 0 : attemptId.hashCode());
result = prime * result + ((cardId == null) ? 0 : cardId.hashCode());
result = prime * result + score;
result = prime * result + (int) (scoreTimeStamp ^ (scoreTimeStamp >>> 32));
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ScoreCard other = (ScoreCard) obj;
if (attemptId == null) {
if (other.attemptId != null)
return false;
} else if (!attemptId.equals(other.attemptId))
return false;
if (cardId == null) {
if (other.cardId != null)
return false;
} else if (!cardId.equals(other.cardId))
return false;
if (score != other.score)
return false;
if (scoreTimeStamp != other.scoreTimeStamp)
return false;
if (userId == null) {
if (other.userId != null)
return false;
} else if (!userId.equals(other.userId))
return false;
return true;
}
#Override
public String toString() {
return "ScoreCard [cardId=" + cardId + ", userId=" + userId + ", attemptId=" + attemptId + ", scoreTimeStamp="
+ scoreTimeStamp + ", score=" + score + "]";
}
}
UserStatsController.java
#RestController
#RequestMapping("/stats")
public class UserStatsController {
private GameService gameService;
#Autowired
public UserStatsController(GameService gameService) {
this.gameService = gameService;
}
#GetMapping
public GameStats getStatsForUser(#RequestParam("userId") Long userId) {
return gameService.retrieveStatsForUser(userId);
}
}
applicaition.properties
server.port=8081
spring.h2.console.enabled=true
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:h2:file:~/gamification;DB_CLOSE_ON_EXIT=FALSE;
spring.jpa.properties.hibernate.show_sql=true
You should change the findByUserIdOrderByScoreTimestampDesc to findByUserIdOrderByScoreTimeStampDesc.
Explanation: The properties of Entity Class must match with the Default Naming Strategy (unless configured specifically.)
I hope, this works.
Your Entity class is having property name as scoreTimeStamp (s in capital for timestamp word), but in Method Declaration, it is ScoreTimestamp (s in lowercase for timestamp word).
PS: By the information you provided in Question and following comments, this should only be the problem.

Use OrderBy with JPARepository

I have a code like this:
public interface BatchExecuteHistoryRepository extends JpaRepository<BatchExecuteHistory, Long> {
Page<BatchExecuteHistory> findByBatchExecuteHistoryIdBatchIdOrderByTimeEndAsc(String batchId, Pageable pageable);
}
Here is my database:
Here is what I got on my website:
Anyone know why the query does not work with Order By time_end ASC???
I tried findByBatchExecuteHistoryIdBatchId(String batchId, Pageable pageable) and got the same result
Notice that BatchExecuteHistoryId is a composite id, and batchId is a element of it
Update, here is my BatchExecuteHistory class:
public class BatchExecuteHistory implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private BatchExecuteHistoryId batchExecuteHistoryId;
#NotNull
#Size(max = 100)
#Column(name = "batch_name", length = 100, nullable = false)
private String batchName;
#NotNull
#Column(name = "status", nullable = false)
private Boolean status;
#NotNull
#Column(name = "time_end", nullable = false)
private Instant timeEnd;
#Size(max = 100)
#Column(name = "error_step", length = 100)
private String errorStep;
#Size(max = 100)
#Column(name = "error_content", length = 100)
private String errorContent;
#Column(name = "row_input")
private Long rowInput;
public BatchExecuteHistoryId getBatchExecuteHistoryId() {
return batchExecuteHistoryId;
}
public void setBatchExecuteHistoryId(BatchExecuteHistoryId batchExecuteHistoryId) {
this.batchExecuteHistoryId = batchExecuteHistoryId;
}
public Boolean getStatus() {
return status;
}
public String getBatchName() {
return batchName;
}
public BatchExecuteHistory batchName(String batchName) {
this.batchName = batchName;
return this;
}
public void setBatchName(String batchName) {
this.batchName = batchName;
}
public Boolean isStatus() {
return status;
}
public BatchExecuteHistory status(Boolean status) {
this.status = status;
return this;
}
public void setStatus(Boolean status) {
this.status = status;
}
public Instant getTimeEnd() {
return timeEnd;
}
public BatchExecuteHistory timeEnd(Instant timeEnd) {
this.timeEnd = timeEnd;
return this;
}
public void setTimeEnd(Instant timeEnd) {
this.timeEnd = timeEnd;
}
public String getErrorStep() {
return errorStep;
}
public BatchExecuteHistory errorStep(String errorStep) {
this.errorStep = errorStep;
return this;
}
public void setErrorStep(String errorStep) {
this.errorStep = errorStep;
}
public String getErrorContent() {
return errorContent;
}
public BatchExecuteHistory errorContent(String errorContent) {
this.errorContent = errorContent;
return this;
}
public void setErrorContent(String errorContent) {
this.errorContent = errorContent;
}
public Long getRowInput() {
return rowInput;
}
public BatchExecuteHistory rowInput(Long rowInput) {
this.rowInput = rowInput;
return this;
}
public void setRowInput(Long rowInput) {
this.rowInput = rowInput;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((batchExecuteHistoryId == null) ? 0 : batchExecuteHistoryId.hashCode());
result = prime * result + ((batchName == null) ? 0 : batchName.hashCode());
result = prime * result + ((errorContent == null) ? 0 : errorContent.hashCode());
result = prime * result + ((errorStep == null) ? 0 : errorStep.hashCode());
result = prime * result + ((rowInput == null) ? 0 : rowInput.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
result = prime * result + ((timeEnd == null) ? 0 : timeEnd.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BatchExecuteHistory other = (BatchExecuteHistory) obj;
if (batchExecuteHistoryId == null) {
if (other.batchExecuteHistoryId != null)
return false;
} else if (!batchExecuteHistoryId.equals(other.batchExecuteHistoryId))
return false;
if (batchName == null) {
if (other.batchName != null)
return false;
} else if (!batchName.equals(other.batchName))
return false;
if (errorContent == null) {
if (other.errorContent != null)
return false;
} else if (!errorContent.equals(other.errorContent))
return false;
if (errorStep == null) {
if (other.errorStep != null)
return false;
} else if (!errorStep.equals(other.errorStep))
return false;
if (rowInput == null) {
if (other.rowInput != null)
return false;
} else if (!rowInput.equals(other.rowInput))
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
if (timeEnd == null) {
if (other.timeEnd != null)
return false;
} else if (!timeEnd.equals(other.timeEnd))
return false;
return true;
}
#Override
public String toString() {
return "BatchExecuteHistory [" + batchExecuteHistoryId.toString() + ", batchName=" + batchName + ", status="
+ status + ", timeEnd=" + timeEnd + ", errorStep=" + errorStep + ", errorContent=" + errorContent
+ ", rowInput=" + rowInput + "]";
}
}
You should add a By before OrderBy, so your method should be: findByBatchExecuteHistoryIdBatchIdByOrderByTimeEndAsc
I think you don't miss naming.See Spring document
OrderBy
findByAgeOrderByLastnameDesc
… where x.age = ?1 order by x.lastname desc
It works well in my environment. I am using 2.6.0 version.
I recommand you check jpa version.and I can't see your BatchExecuteHistoryId class.
Anyway Try it for checking it works well in your environment.
Database
CREATE TABLE MEMBER
(
id character varying(10),
batch_id character varying(10),
create_datetime timestamp without time zone NOT NULL,
CONSTRAINT MEMBER_PK
PRIMARY KEY (id,batch_id)
);
INSERT into MEMBER (id,create_datetime,batch_id) VALUES ('USER1','2021/11/20 14:00:00','1');
INSERT into MEMBER (id,create_datetime,batch_id) VALUES ('USER2','2021/11/15 14:00:00','1');
INSERT into MEMBER (id,create_datetime,batch_id) VALUES ('USER3','2021/11/10 14:00:00','1');
Entity
#Entity(name = "Member")
#Table(name = "member")
#ToString
#Data
public class MemberEntity {
#EmbeddedId
private MemberPk batchExecuteHistoryId;
#Column(name = "create_datetime")
private LocalDateTime createDateTime;
}
Pk of Entity
#Embeddable
#ToString
public class MemberPk implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
#Column(name = "batch_id")
private String batchId;
}
Repository
#Repository
public interface MemberRepository extends JpaRepository<MemberEntity, String> {
public List<MemberEntity> findByBatchExecuteHistoryIdBatchIdOrderByCreateDateTimeAsc(String batchId, Pageable pageable);
}
Service
#Service
public class MemberService {
private final MemberRepository memberRepository;
#Autowired
public MemberService(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
#PostConstruct
public void findAllMember() {
List<MemberEntity> memberEntitys = memberRepository.findAll();
//MemberEntity(batchExecuteHistoryId=MemberPk(id=USER1, batchId=1), createDateTime=2021-11-20T14:00)
//MemberEntity(batchExecuteHistoryId=MemberPk(id=USER2, batchId=1), createDateTime=2021-11-15T14:00)
//MemberEntity(batchExecuteHistoryId=MemberPk(id=USER3, batchId=1), createDateTime=2021-11-10T14:00)
memberEntitys.forEach(System.out::println);
System.out.println("----------------------------");
//MemberEntity(batchExecuteHistoryId=MemberPk(id=USER3, batchId=1), createDateTime=2021-11-10T14:00)
//MemberEntity(batchExecuteHistoryId=MemberPk(id=USER2, batchId=1), createDateTime=2021-11-15T14:00)
List<MemberEntity> memberEntitysWithOrderBy = memberRepository.findByBatchExecuteHistoryIdBatchIdOrderByCreateDateTimeAsc("1",PageRequest.of(0, 2));
memberEntitysWithOrderBy.forEach(System.out::println);
}
}

Hibernate JPA 2.0, Spring, Postgres - Exception: The column index is out of range

I am using Hibernate 3.6 with a PostgreSQL database. I have a one-to-many relationship mapped with a composite key using #IdClass. When I invoke a SaveOrUpdate on the owning entity, I receive an exception when hibernate attempts to insert the child relationsip.
The exception is:
org.postgresql.util.PSQLException: The column index is out of range: 4, number of columns: 3.
at org.postgresql.core.v3.SimpleParameterList.bind(SimpleParameterList.java:56)
at org.postgresql.core.v3.SimpleParameterList.setNull(SimpleParameterList.java:141)
at org.postgresql.jdbc2.AbstractJdbc2Statement.setNull(AbstractJdbc2Statement.java:1215)
at org.postgresql.jdbc3.AbstractJdbc3Statement.setNull(AbstractJdbc3Statement.java:1490)
at org.postgresql.jdbc4.AbstractJdbc4Statement.setNull(AbstractJdbc4Statement.java:84)
at com.zaxxer.hikari.proxy.PreparedStatementJavassistProxy.setNull(PreparedStatementJavassistProxy.java)
at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:78)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:283)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:278)
at org.hibernate.type.ComponentType.nullSafeSet(ComponentType.java:317)
at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:2195)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2431)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2875)
at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:79)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:184)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
...
The entity that is failing looks like this (it includes the class annotated in #IdClass):
#Entity
#IdClass(DsbRowDataDashboard.RowDataDashboardPK.class)
#Table(name = "dsb_row_data_dashboard")
public class DsbRowDataDashboard implements Serializable {
private static final long serialVersionUID = 2036988934943807608L;
public static final String NQ_GetRowsInvolvedForWorkstreamMoveUp = "DsbRowDataDashboard.getRowsInvolvedForWorkstreamMoveUp";
public static final String NQ_GetRowsInvolvedForWorkstreamMoveDown = "DsbRowDataDashboard.getRowsInvolvedForWorkstreamMoveDown";
public static final String NQ_GetRowsInvolvedForSubtaskMoveUp = "DsbRowDataDashboard.getRowsInvolvedForSubtaskMoveUp";
public static final String NQ_GetRowsInvolvedForSubtaskMoveDown = "DsbRowDataDashboard.getRowsInvolvedForSubtaskMoveDown";
public static final String NQ_FindMaxPositionForWorkstream = "DsbRowDataDashboard.findMaxPositionForWorkstream";
public static final String NQ_FindMaxPositionForSubtask = "DsbRowDataDashboard.findMaxPositionForSubtask";
#Id
#Column(name = "row_data_id", insertable = false, updatable = false)
private Long rowDataId;
#Id
#Column(name = "dashboard_id", insertable = false, updatable = false)
private Long dashboardId;
#Column(name = "row_position")
private Long position;
#ManyToOne// DO NOT cascade anything here
#JoinColumn(name = "row_data_id")
private DsbRowData rowData;
#ManyToOne // DO NOT cascade anything here
#JoinColumn(name = "dashboard_id")
private DsbDashboard dashboard;
public DsbRowDataDashboard() {
}
public DsbRowDataDashboard(DsbRowData rowData, DsbDashboard dsbDashboard, Long position) {
this.rowData = rowData;
this.dashboard = dsbDashboard;
this.position = position;
}
public Long getRowDataId() {
return rowDataId;
}
public void setRowDataId(Long rowDataId) {
this.rowDataId = rowDataId;
}
public Long getDashboardId() {
return dashboardId;
}
public void setDashboardId(Long dashboardId) {
this.dashboardId = dashboardId;
}
public Long getPosition() {
return position;
}
public void setPosition(Long position) {
this.position = position;
}
public DsbRowData getRowData() {
return rowData;
}
public void setRowData(DsbRowData rowData) {
this.rowData = rowData;
}
public DsbDashboard getDashboard() {
return dashboard;
}
public void setDashboard(DsbDashboard dashboard) {
this.dashboard = dashboard;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((rowDataId == null) ? 0 : rowDataId.hashCode());
result = prime * result + ((dashboardId == null) ? 0 : dashboardId.hashCode());
result = prime * result + ((position == null) ? 0 : position.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof DsbRowDataDashboard))
return false;
DsbRowDataDashboard other = (DsbRowDataDashboard) obj;
if (rowDataId == null) {
if (other.rowDataId != null)
return false;
} else if (!rowDataId.equals(other.rowDataId))
return false;
if (dashboardId == null) {
if (other.dashboardId != null)
return false;
} else if (!dashboardId.equals(other.dashboardId))
return false;
if (position == null) {
if (other.position != null)
return false;
} else if (!position.equals(other.position))
return false;
return true;
}
#Override
public String toString() {
return "DsbRowDashboard [rowDataid=" + rowDataId + ", dashboardId = " + dashboardId + "position=" + position + "]";
}
public static class RowDataDashboardPK implements Serializable {
private static final long serialVersionUID = -1665119146485718132L;
protected Long rowDataId;
protected Long dashboardId;
public RowDataDashboardPK() {
}
public RowDataDashboardPK(Long rowDataId, Long dashboardId) {
this.rowDataId = rowDataId;
this.dashboardId = dashboardId;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((rowDataId == null) ? 0 : rowDataId.hashCode());
result = prime * result + ((dashboardId == null) ? 0 : dashboardId.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof RowDataDashboardPK))
return false;
RowDataDashboardPK other = (RowDataDashboardPK) obj;
if (rowDataId == null) {
if (other.rowDataId != null)
return false;
} else if (!rowDataId.equals(other.rowDataId))
return false;
if (dashboardId == null) {
if (other.dashboardId != null)
return false;
} else if (!dashboardId.equals(other.dashboardId))
return false;
return true;
}
}
}
The relationship on the parent looks like this:
#OneToMany(fetch = FetchType.LAZY, mappedBy = "rowData", orphanRemoval = true)
#Cascade({CascadeType.ALL})
private Set<DsbRowDataDashboard> rowPositions = new HashSet<DsbRowDataDashboard>(0);
I've enabled all the relevant debug for hibernate to see the sql and debug. This is what happens that leads to failure:
[DEBUG] [ org.hibernate.SQL:] [ 111] -
/* insert com.myapp.model.DsbRowDataDashboard
*/ insert
into
dsb_row_data_dashboard
(dashboard_id, row_position, row_data_id)
values
(?, ?, ?)
[TRACE] [ org.hibernate.type.descriptor.sql.BasicBinder:] [ 82] - binding parameter [1] as [BIGINT] - 1392
[TRACE] [ org.hibernate.type.descriptor.sql.BasicBinder:] [ 82] - binding parameter [2] as [BIGINT] - 0
[TRACE] [ org.hibernate.type.descriptor.sql.BasicBinder:] [ 82] - binding parameter [3] as [BIGINT] - 50
[TRACE] [ org.hibernate.type.descriptor.sql.BasicBinder:] [ 70] - binding parameter [4] as [BIGINT] - <null>
[DEBUG] [ org.hibernate.jdbc.AbstractBatcher:] [ 418] - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
The previous sql to this is the parent row being inserted and it is a success. Then hibernate attempts to insert the child and it fails. The entire transaction is rolled back.
I set both sides of the relationship and then call a hibernate saveorupdate:
DsbRowDataDashboard rowDataDashboard = new DsbRowDataDashboard(rowData, rowData.getDsbDashboard(), maxpos);
rowData.getRowPositions().add(rowDataDashboard);
dsbRowDataDao.update(rowData);
-----
public T update(T obj) {
getSessionFactory().getCurrentSession().saveOrUpdate(obj);
return obj;
}
I've seen two other questions with pretty much the exact same issue, but no real solution.
Here is one that is very close to this same issue:
https://stackoverflow.com/questions/37092382/spring-data-jpa-column-index-out-of-range
Any insight is greatly appreciated.
Thank you.

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

Hibernate create too many sql

I have one class named MachineSalesReport:
#Entity
#Table(name = "machine_report")
public class MachineSalesReport implements Serializable, Cloneable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column
private int id;
#Column(name = "avery_sales_order_no")
private String averySalesOrderNo;
#Column(name = "editor")
private String editor;
#Column(name = "edit_date")
private Date editDate;
#Column(name = "ship_out_date")
private Date shipOutDate;
#Column(name = "remarks")
private String remarks;
#Column(name = "nature_of_sales")
private String natureOfSales;
#Column(name = "supply_agreement")
private String supplyagreement;
#Column(name = "retailer")
private String retailer;
#Column(name = "program")
private String program;
#Column(name = "product_line")
private String productLine;
#Column(name = "is_final")
private String isFinal;
#Column(name = "exists")
private String exists;
#Column(name = "contract_flag")
private boolean contractFlag;
#Column(name = "installation_flag")
private boolean installationFlag;
#Column(name = "last_update_date")
private Timestamp lastUpdateTime;
#Column(name = " last_update_editor")
private String lastUpdateEditor;
#Column(name = "email_flag")
private boolean emailFlag;
#OneToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
#JoinColumn(name = "internal_information_id")
private InternalInformation internalInformation;
#OneToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
#JoinColumn(name = "customer_information_id")
private CustomerInformation customerInformation;
#OneToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
#JoinColumn(name = "installation_information_id")
private InstallationInformation installationInformation;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "machineSalesReport")
private List<ContractsAndWarranty> contracts;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAverySalesOrderNo() {
return averySalesOrderNo;
}
public void setAverySalesOrderNo(String averySalesOrderNo) {
this.averySalesOrderNo = averySalesOrderNo;
}
public String getEditor() {
return editor;
}
public void setEditor(String editor) {
this.editor = editor;
}
public Date getEditDate() {
return editDate;
}
public void setEditDate(Date editDate) {
this.editDate = editDate;
}
public Date getShipOutDate() {
return shipOutDate;
}
public void setShipOutDate(Date shipOutDate) {
this.shipOutDate = shipOutDate;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getNatureOfSales() {
return natureOfSales;
}
public boolean isEmailFlag() {
return emailFlag;
}
public void setEmailFlag(boolean emailFlag) {
this.emailFlag = emailFlag;
}
public void setNatureOfSales(String natureOfSales) {
this.natureOfSales = natureOfSales;
}
public String getRetailer() {
return retailer;
}
public void setRetailer(String retailer) {
this.retailer = retailer;
}
public String getProgram() {
return program;
}
public void setProgram(String program) {
this.program = program;
}
public String getProductLine() {
return productLine;
}
public void setProductLine(String productLine) {
this.productLine = productLine;
}
public InternalInformation getInternalInformation() {
return internalInformation;
}
public void setInternalInformation(InternalInformation internalInformation) {
this.internalInformation = internalInformation;
}
public CustomerInformation getCustomerInformation() {
return customerInformation;
}
public void setCustomerInformation(CustomerInformation customerInformation) {
this.customerInformation = customerInformation;
}
public InstallationInformation getInstallationInformation() {
return installationInformation;
}
public void setInstallationInformation(
InstallationInformation installationInformation) {
this.installationInformation = installationInformation;
}
public String getIsFinal() {
return isFinal;
}
public void setIsFinal(String isFinal) {
this.isFinal = isFinal;
}
public String getExists() {
return exists;
}
public void setExists(String exists) {
this.exists = exists;
}
public boolean isContractFlag() {
return contractFlag;
}
public void setContractFlag(boolean contractFlag) {
this.contractFlag = contractFlag;
}
public boolean isInstallationFlag() {
return installationFlag;
}
public void setInstallationFlag(boolean installationFlag) {
this.installationFlag = installationFlag;
}
public List<ContractsAndWarranty> getContracts() {
return contracts;
}
public void setContracts(List<ContractsAndWarranty> contracts) {
this.contracts = contracts;
}
public Date getLastUpdateTime() {
return lastUpdateTime;
}
public String getLastUpdateEditor() {
return lastUpdateEditor;
}
public void setLastUpdateTime(Timestamp lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
public void setLastUpdateEditor(String lastUpdateEditor) {
this.lastUpdateEditor = lastUpdateEditor;
}
public String getSupplyagreement() {
return supplyagreement;
}
public void setSupplyagreement(String supplyagreement) {
this.supplyagreement = supplyagreement;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((averySalesOrderNo == null) ? 0 : averySalesOrderNo
.hashCode());
result = prime * result + (contractFlag ? 1231 : 1237);
result = prime * result
+ ((contracts == null) ? 0 : contracts.hashCode());
result = prime
* result
+ ((customerInformation == null) ? 0 : customerInformation
.hashCode());
result = prime * result
+ ((editDate == null) ? 0 : editDate.hashCode());
result = prime * result + ((editor == null) ? 0 : editor.hashCode());
result = prime * result + ((exists == null) ? 0 : exists.hashCode());
result = prime * result + id;
result = prime * result + (installationFlag ? 1231 : 1237);
result = prime
* result
+ ((installationInformation == null) ? 0
: installationInformation.hashCode());
result = prime
* result
+ ((internalInformation == null) ? 0 : internalInformation
.hashCode());
result = prime * result + ((isFinal == null) ? 0 : isFinal.hashCode());
result = prime * result
+ ((natureOfSales == null) ? 0 : natureOfSales.hashCode());
result = prime * result
+ ((productLine == null) ? 0 : productLine.hashCode());
result = prime * result + ((program == null) ? 0 : program.hashCode());
result = prime * result + ((remarks == null) ? 0 : remarks.hashCode());
result = prime * result
+ ((retailer == null) ? 0 : retailer.hashCode());
result = prime * result
+ ((shipOutDate == null) ? 0 : shipOutDate.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MachineSalesReport other = (MachineSalesReport) obj;
if (averySalesOrderNo == null) {
if (other.averySalesOrderNo != null)
return false;
} else if (!averySalesOrderNo.equals(other.averySalesOrderNo))
return false;
if (contractFlag != other.contractFlag)
return false;
if (contracts == null) {
if (other.contracts != null)
return false;
} else if (!contracts.equals(other.contracts))
return false;
if (customerInformation == null) {
if (other.customerInformation != null)
return false;
} else if (!customerInformation.equals(other.customerInformation))
return false;
if (editDate == null) {
if (other.editDate != null)
return false;
} else if (!editDate.equals(other.editDate))
return false;
if (editor == null) {
if (other.editor != null)
return false;
} else if (!editor.equals(other.editor))
return false;
if (exists == null) {
if (other.exists != null)
return false;
} else if (!exists.equals(other.exists))
return false;
if (id != other.id)
return false;
if (installationFlag != other.installationFlag)
return false;
if (installationInformation == null) {
if (other.installationInformation != null)
return false;
} else if (!installationInformation
.equals(other.installationInformation))
return false;
if (internalInformation == null) {
if (other.internalInformation != null)
return false;
} else if (!internalInformation.equals(other.internalInformation))
return false;
if (isFinal == null) {
if (other.isFinal != null)
return false;
} else if (!isFinal.equals(other.isFinal))
return false;
if (natureOfSales == null) {
if (other.natureOfSales != null)
return false;
} else if (!natureOfSales.equals(other.natureOfSales))
return false;
if (productLine == null) {
if (other.productLine != null)
return false;
} else if (!productLine.equals(other.productLine))
return false;
if (program == null) {
if (other.program != null)
return false;
} else if (!program.equals(other.program))
return false;
if (remarks == null) {
if (other.remarks != null)
return false;
} else if (!remarks.equals(other.remarks))
return false;
if (retailer == null) {
if (other.retailer != null)
return false;
} else if (!retailer.equals(other.retailer))
return false;
if (shipOutDate == null) {
if (other.shipOutDate != null)
return false;
} else if (!shipOutDate.equals(other.shipOutDate))
return false;
return true;
}
#Override
public String toString() {
return "MachineSalesReport [id=" + id + ", averySalesOrderNo="
+ averySalesOrderNo + ", editor=" + editor + ", editDate="
+ editDate + ", shipOutDate=" + shipOutDate + ", remarks="
+ remarks + ", natureOfSales=" + natureOfSales + ", retailer="
+ retailer + ", program=" + program + ", productLine="
+ productLine + ", isFinal=" + isFinal + ", exists=" + exists
+ ", contractFlag=" + contractFlag + ", installationFlag="
+ installationFlag + ", internalInformation="
+ internalInformation + ", customerInformation="
+ customerInformation + ", installationInformation="
+ installationInformation + ", contracts=" + contracts + "]";
}
#Override
public Object clone() {
MachineSalesReport report = null;
try {
report = (MachineSalesReport) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
List<ContractsAndWarranty> contracts = new ArrayList<ContractsAndWarranty>();
for (int i = 0; i < this.contracts.size(); i++) {
ContractsAndWarranty contract = (ContractsAndWarranty) this.contracts
.get(i).clone();
contracts.add(contract);
}
report.setContracts(contracts);
return report;
}
}
i have a Dao is:
System.out.println("*************begin**");
Criteria dc = sessionFactory.getCurrentSession().createCriteria(MachineSalesReport.class,"mr")
.createAlias("mr.installationInformation", "install").createAlias("mr.customerInformation","customer").createAlias("mr.internalInformation", "internal");
dc.setMaxResults(1);
List<MachineSalesReport> reports= dc.list();
System.out.println("*************end**");
and run the dao , my control show the sql have 3 sql:
Hibernate: select this_.id as id5_6_, this_.avery_sales_order_no as avery2_5_6_, this_.contract_flag as contract3_5_6_, this_.customer_information_id as customer19_5_6_, this_.edit_date as edit4_5_6_, this_.editor as editor5_6_, this_.email_flag as email6_5_6_, this_.exists as exists5_6_, this_.installation_flag as installa8_5_6_, this_.installation_information_id as install20_5_6_, this_.internal_information_id as internal21_5_6_, this_.is_final as is9_5_6_, this_. last_update_editor as column10_5_6_, this_.last_update_date as last11_5_6_, this_.nature_of_sales as nature12_5_6_, this_.product_line as product13_5_6_, this_.program as program5_6_, this_.remarks as remarks5_6_, this_.retailer as retailer5_6_, this_.ship_out_date as ship17_5_6_, this_.supply_agreement as supply18_5_6_, customer2_.id as id1_0_, customer2_.bill_to_company_address_cn as bill2_1_0_, customer2_.bill_to_company_address_en as bill3_1_0_, customer2_.bill_to_company_name as bill4_1_0_, customer2_.bill_to_code as bill5_1_0_, customer2_.bill_to_country as bill6_1_0_, customer2_.customer_email as customer7_1_0_, customer2_.customer_fax as customer8_1_0_, customer2_.customer_phone as customer9_1_0_, customer2_.customer_name as customer10_1_0_, customer2_.ship_from as ship11_1_0_, customer2_.ship_to_company_address_cn as ship12_1_0_, customer2_.ship_to_company_address_en as ship13_1_0_, customer2_.ship_to_company_name as ship14_1_0_, machinesal6_.id as id5_1_, machinesal6_.avery_sales_order_no as avery2_5_1_, machinesal6_.contract_flag as contract3_5_1_, machinesal6_.customer_information_id as customer19_5_1_, machinesal6_.edit_date as edit4_5_1_, machinesal6_.editor as editor5_1_, machinesal6_.email_flag as email6_5_1_, machinesal6_.exists as exists5_1_, machinesal6_.installation_flag as installa8_5_1_, machinesal6_.installation_information_id as install20_5_1_, machinesal6_.internal_information_id as internal21_5_1_, machinesal6_.is_final as is9_5_1_, machinesal6_. last_update_editor as column10_5_1_, machinesal6_.last_update_date as last11_5_1_, machinesal6_.nature_of_sales as nature12_5_1_, machinesal6_.product_line as product13_5_1_, machinesal6_.program as program5_1_, machinesal6_.remarks as remarks5_1_, machinesal6_.retailer as retailer5_1_, machinesal6_.ship_out_date as ship17_5_1_, machinesal6_.supply_agreement as supply18_5_1_, install1_.id as id2_2_, install1_.customer_email as customer2_2_2_, install1_.customer_fax as customer3_2_2_, install1_.customer_name as customer4_2_2_, install1_.customer_phone as customer5_2_2_, install1_.factory_address_cn as factory6_2_2_, install1_.factory_address_en as factory7_2_2_, install1_.factory_name as factory8_2_2_, machinesal8_.id as id5_3_, machinesal8_.avery_sales_order_no as avery2_5_3_, machinesal8_.contract_flag as contract3_5_3_, machinesal8_.customer_information_id as customer19_5_3_, machinesal8_.edit_date as edit4_5_3_, machinesal8_.editor as editor5_3_, machinesal8_.email_flag as email6_5_3_, machinesal8_.exists as exists5_3_, machinesal8_.installation_flag as installa8_5_3_, machinesal8_.installation_information_id as install20_5_3_, machinesal8_.internal_information_id as internal21_5_3_, machinesal8_.is_final as is9_5_3_, machinesal8_. last_update_editor as column10_5_3_, machinesal8_.last_update_date as last11_5_3_, machinesal8_.nature_of_sales as nature12_5_3_, machinesal8_.product_line as product13_5_3_, machinesal8_.program as program5_3_, machinesal8_.remarks as remarks5_3_, machinesal8_.retailer as retailer5_3_, machinesal8_.ship_out_date as ship17_5_3_, machinesal8_.supply_agreement as supply18_5_3_, internal3_.id as id3_4_, internal3_.avery_entity_name as avery2_3_4_, internal3_.city as city3_4_, internal3_.country as country3_4_, internal3_.csr_email as csr5_3_4_, internal3_.csr_name as csr6_3_4_, internal3_.csr_phone as csr7_3_4_, internal3_.salesperson_email as salesper8_3_4_, internal3_.salesperson_name as salesper9_3_4_, internal3_.salesperson_phone as salespe10_3_4_, machinesal10_.id as id5_5_, machinesal10_.avery_sales_order_no as avery2_5_5_, machinesal10_.contract_flag as contract3_5_5_, machinesal10_.customer_information_id as customer19_5_5_, machinesal10_.edit_date as edit4_5_5_, machinesal10_.editor as editor5_5_, machinesal10_.email_flag as email6_5_5_, machinesal10_.exists as exists5_5_, machinesal10_.installation_flag as installa8_5_5_, machinesal10_.installation_information_id as install20_5_5_, machinesal10_.internal_information_id as internal21_5_5_, machinesal10_.is_final as is9_5_5_, machinesal10_. last_update_editor as column10_5_5_, machinesal10_.last_update_date as last11_5_5_, machinesal10_.nature_of_sales as nature12_5_5_, machinesal10_.product_line as product13_5_5_, machinesal10_.program as program5_5_, machinesal10_.remarks as remarks5_5_, machinesal10_.retailer as retailer5_5_, machinesal10_.ship_out_date as ship17_5_5_, machinesal10_.supply_agreement as supply18_5_5_ from machine_report this_ inner join customer_information customer2_ on this_.customer_information_id=customer2_.id left outer join machine_report machinesal6_ on customer2_.id=machinesal6_.customer_information_id inner join installation_information install1_ on this_.installation_information_id=install1_.id left outer join machine_report machinesal8_ on install1_.id=machinesal8_.installation_information_id inner join internal_information internal3_ on this_.internal_information_id=internal3_.id left outer join machine_report machinesal10_ on internal3_.id=machinesal10_.internal_information_id limit ?
Hibernate: select machinesal0_.id as id5_0_, machinesal0_.avery_sales_order_no as avery2_5_0_, machinesal0_.contract_flag as contract3_5_0_, machinesal0_.customer_information_id as customer19_5_0_, machinesal0_.edit_date as edit4_5_0_, machinesal0_.editor as editor5_0_, machinesal0_.email_flag as email6_5_0_, machinesal0_.exists as exists5_0_, machinesal0_.installation_flag as installa8_5_0_, machinesal0_.installation_information_id as install20_5_0_, machinesal0_.internal_information_id as internal21_5_0_, machinesal0_.is_final as is9_5_0_, machinesal0_. last_update_editor as column10_5_0_, machinesal0_.last_update_date as last11_5_0_, machinesal0_.nature_of_sales as nature12_5_0_, machinesal0_.product_line as product13_5_0_, machinesal0_.program as program5_0_, machinesal0_.remarks as remarks5_0_, machinesal0_.retailer as retailer5_0_, machinesal0_.ship_out_date as ship17_5_0_, machinesal0_.supply_agreement as supply18_5_0_ from machine_report machinesal0_ where machinesal0_.installation_information_id=?
Hibernate: select machinesal0_.id as id5_0_, machinesal0_.avery_sales_order_no as avery2_5_0_, machinesal0_.contract_flag as contract3_5_0_, machinesal0_.customer_information_id as customer19_5_0_, machinesal0_.edit_date as edit4_5_0_, machinesal0_.editor as editor5_0_, machinesal0_.email_flag as email6_5_0_, machinesal0_.exists as exists5_0_, machinesal0_.installation_flag as installa8_5_0_, machinesal0_.installation_information_id as install20_5_0_, machinesal0_.internal_information_id as internal21_5_0_, machinesal0_.is_final as is9_5_0_, machinesal0_. last_update_editor as column10_5_0_, machinesal0_.last_update_date as last11_5_0_, machinesal0_.nature_of_sales as nature12_5_0_, machinesal0_.product_line as product13_5_0_, machinesal0_.program as program5_0_, machinesal0_.remarks as remarks5_0_, machinesal0_.retailer as retailer5_0_, machinesal0_.ship_out_date as ship17_5_0_, machinesal0_.supply_agreement as supply18_5_0_ from machine_report machinesal0_ where machinesal0_.internal_information_id=?
why the sql is so many? i want the first sql,and get the MachineSalesReport ,include the customerInformation and InternalInformation and InstallInformation

Categories

Resources