Use OrderBy with JPARepository - java

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

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.

How to create object in object Spring JPA (Jhipster)

I am beginner using java and spring jpa (expecially Jhipster). I want to create object in object like this :
But I always get like this :
property buildingsDTO always empty, this is my code, please correct my code in order I get like first picture.
location.java (Domain)
public class Location implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Column(name = "content_location", nullable = false)
private String content_location;
#OneToMany(mappedBy = "location")
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Building> buildings = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getContent_location() {
return content_location;
}
public Location content_location(String content_location) {
this.content_location = content_location;
return this;
}
public void setContent_location(String content_location) {
this.content_location = content_location;
}
public Set<Building> getBuildings() {
return buildings;
}
public Location buildings(Set<Building> buildings) {
this.buildings = buildings;
return this;
}
public Location addBuilding(Building building) {
this.buildings.add(building);
building.setLocation(this);
return this;
}
public Location removeBuilding(Building building) {
this.buildings.remove(building);
building.setLocation(null);
return this;
}
public void setBuildings(Set<Building> buildings) {
this.buildings = buildings;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Location location = (Location) o;
if (location.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), location.getId());
}
#Override
public int hashCode() {
return Objects.hashCode(getId());
}
#Override
public String toString() {
return "Location{" +
"id=" + getId() +
", content_location='" + getContent_location() + "'" +
"}";
}}
locationDTO.java
public class LocationDTO implements Serializable {
private Long id;
#NotNull
private String content_location;
private Set<BuildingDTO> buildings = new HashSet<>();
public Set<BuildingDTO> getBuildingsDTO() {
return buildings;
}
public void setBuildingsDTO(Set<BuildingDTO> buildings) {
this.buildings = buildings;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getContent_location() {
return content_location;
}
public void setContent_location(String content_location) {
this.content_location = content_location;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LocationDTO locationDTO = (LocationDTO) o;
if(locationDTO.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), locationDTO.getId());
}
#Override
public int hashCode() {
return Objects.hashCode(getId());
}
#Override
public String toString() {
return "LocationDTO{" +
"id=" + getId() +
", content_location='" + getContent_location() + "'" +
"}";
}}
locationMapper.java
public interface LocationMapper extends EntityMapper <LocationDTO, Location> {
#Mapping(target = "buildings", ignore = true)
Location toEntity(LocationDTO locationDTO);
default Location fromId(Long id) {
if (id == null) {
return null;
}
Location location = new Location();
location.setId(id);
return location;
}}
buildingDTO.java
public class BuildingDTO implements Serializable {
private Long id;
#NotNull
private String content_building;
private Long locationId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getContent_building() {
return content_building;
}
public void setContent_building(String content_building) {
this.content_building = content_building;
}
public Long getLocationId() {
return locationId;
}
public void setLocationId(Long locationId) {
this.locationId = locationId;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BuildingDTO buildingDTO = (BuildingDTO) o;
if(buildingDTO.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), buildingDTO.getId());
}
#Override
public int hashCode() {
return Objects.hashCode(getId());
}
#Override
public String toString() {
return "BuildingDTO{" +
"id=" + getId() +
", content_building='" + getContent_building() + "'" +
"}";
}}
please anyone help me.
thanks.
By default jHipster will mark any OneToMany entity relationships as #JsonIgnore so that the Set of buildings is not returned in the JSON:
#OneToMany(mappedBy = "location")
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Building> buildings = new HashSet<>();
If you want this to show up in the JSON then you should remove that annotation and also mark it with an eager loading strategy so that the set of buildings are loaded as you expect:
#OneToMany(mappedBy = "location", fetch = FetchType.EAGER)
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Building> buildings = new HashSet<>();

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

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.

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

oracle db id column auto generate JPA JSF

I have a basic problem with my oracle database table whereas I use JPA.
My problem is, I create the table in the database by adding it an ID column. When I turn back to my JPA project, and when I try to create new entry it doesn't create ID for the new one. It always says: An error occurred attempting to roll back the transaction.
I search about the issue. It basically doesn't auto-generate the ID value. Here is my JPA controller class:
#Entity
#Table(name = "PROJECTS", catalog = "", schema = "PROJETAKIP")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Projects.findAll", query = "SELECT p FROM Projects p"),
#NamedQuery(name = "Projects.findById", query = "SELECT p FROM Projects p WHERE p.id = :id"),
#NamedQuery(name = "Projects.findByProject", query = "SELECT p FROM Projects p WHERE p.project = :project")})
public class Projects implements Serializable {
private static final long serialVersionUID = 1L;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Id
#Basic(optional = false)
#Column(name = "ID", nullable = false, precision = 0, scale = -127)
#GeneratedValue(strategy= GenerationType.SEQUENCE)
private BigDecimal id;
#Column(name = "PROJECT", length = 255)
private String project;
public Projects() {
}
public Projects(BigDecimal id) {
this.id = id;
}
public BigDecimal getId() {
return id;
}
public void setId(BigDecimal id) {
this.id = id;
}
public String getProject() {
return project;
}
public void setProject(String project) {
this.project = project;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Projects)) {
return false;
}
Projects other = (Projects) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.ibb.souce.Projects[ id=" + id + " ]";
}
}
and here is my JSFClass:
#ManagedBean(name = "projectsController")
#SessionScoped
public class ProjectsController implements Serializable {
#Resource
private UserTransaction utx = null;
#PersistenceUnit(unitName = "DenemelerPU")
private EntityManagerFactory emf = null;
private Projects current;
private DataModel items = null;
private ProjectsJpaController jpaController = null;
private PaginationHelper pagination;
private int selectedItemIndex;
public ProjectsController() {
}
public Projects getSelected() {
if (current == null) {
current = new Projects();
selectedItemIndex = -1;
}
return current;
}
private ProjectsJpaController getJpaController() {
if (jpaController == null) {
jpaController = new ProjectsJpaController(utx, emf);
}
return jpaController;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return getJpaController().getProjectsCount();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(getJpaController().findProjectsEntities(getPageSize(), getPageFirstItem()));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (Projects) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new Projects();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getJpaController().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ProjectsCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (Projects) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}
public String update() {
try {
getJpaController().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ProjectsUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (Projects) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
recreatePagination();
recreateModel();
return "List";
}
public String destroyAndView() {
performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}
private void performDestroy() {
try {
getJpaController().destroy(current.getId());
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ProjectsDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getJpaController().getProjectsCount();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getJpaController().findProjectsEntities(1, selectedItemIndex).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
private void recreatePagination() {
pagination = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(getJpaController().findProjectsEntities(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(getJpaController().findProjectsEntities(), true);
}
#FacesConverter(forClass = Projects.class)
public static class ProjectsControllerConverter implements Converter {
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
ProjectsController controller = (ProjectsController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "projectsController");
return controller.getJpaController().findProjects(getKey(value));
}
java.math.BigDecimal getKey(String value) {
java.math.BigDecimal key;
key = new java.math.BigDecimal(value);
return key;
}
String getStringKey(java.math.BigDecimal value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Projects) {
Projects o = (Projects) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Projects.class.getName());
}
}
}
}
When I assign the ID manually it works perfectly. But what I want is, it has to auto-generate the value. How to overcome this?
my trigger: DELIMITER ##
CREATE OR REPLACE TRIGGER PROJETAKIP.PROJECTS_TRIGGER BEFORE INSERT ON PROJECTS REFERENCING NEW AS NEW FOR EACH ROW BEGIN SELECT PROJECTS_SEQUENCE.nextval INTO :NEW.ID FROM dual;END; ##
DELIMITER ;
Sequence startegy
This is how you should use the sequence generator:
#GeneratedValue(strategy= GenerationType.SEQUENCE, generator="seq")
And on the class: (eg. after the #Entity)
#SequenceGenerator(name="seq", sequenceName="PROJECTS_SEQUENCE", initialValue=1)
This should work for you.
While saving the object i had the same error.
My reason was because of adding MIN range of 3 digits to id value.
By default auto generated id will start from 1, 2, 3 ...
I did:
#Id #GeneratedValue
#Basic(optional = false)
#Size(min = 1, max = 64, message = "ID must be between 1 and 64 characters")
private String id;
So - in your case - be careful with your id annotations - try to launch without scale, min and max values - see the result. For example, try:
#Id
#Basic(optional = false)
#Column(name = "ID")
#GeneratedValue(strategy= GenerationType.AUTO)
private BigDecimal id;

Categories

Resources