my entities have ManyToMaany relationship
Ex: If my Businessunit class already has 3 user associated after adding a new one it removes old 3 values and adds the new one in to db
and event triggers once for addition and once for removed
and when i remove this listener it works as expected
those Aduditable and AuditableInsert are marker interfaces on which i check if i need to forward the call or not
#Entity
#Setter
#Getter
#Table(name = "business_unit" ,indexes = {
#Index(name = "tenantIndx", columnList = "TENANT")
})
#SuperBuilder
#NoArgsConstructor
#AllArgsConstructor
#EqualsAndHashCode(callSuper = true)
public class BusinessUnitJpaEntitiy extends AbstractTenantJpaEntity implements Auditable{
private static final long serialVersionUID = -1123383144979037984L;
#Getter
#Column(name = "NAME")
String name;
#Getter
#Column(name = "DESCRIPTION")
String description;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(
name = "business_unit_user",
joinColumns={#JoinColumn(name ="business_unit_id")},
inverseJoinColumns = { #JoinColumn(name="user_id") }
)
private Set<User> businessUsers;
public Set<User> fetchBusinessUsers() {
return businessUsers;
}
#Column(name = "DISPLAY_SEQUENCE_NUM")
protected Long displaySequenceNum;
#Column(name = "UNIQUE_SEQUENCE_ID",unique = true)
protected String uniqueSequenceId;
}
#Entity
#Getter
#Setter
#Table(name = "user")
#NoArgsConstructor
#SuperBuilder
#ToString(callSuper = true,exclude = {"password"})
public class User extends AbstractTenantJpaEntity implements AuditableInsert{
private static final long serialVersionUID = 65981149772133526L;
#Getter
#Column(name = "PROVIDER_USER_ID")
private String providerUserId;
#Getter
private String email;
#Column(name = "enabled", columnDefinition = "BIT", length = 1)
private boolean enabled;
#Column(name = "DISPLAY_NAME")
private String displayName;
private String password;
private String provider;
#Column(name = "DISPLAY_SEQUENCE_NUM")
protected Long displaySequenceNum;
#Column(name = "UNIQUE_SEQUENCE_ID",unique = true)
protected String uniqueSequenceId;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(
name = "business_unit_user",
joinColumns={#JoinColumn(name ="user_id")},
inverseJoinColumns = { #JoinColumn(name="business_unit_id") }
)
Set<BusinessUnitJpaEntitiy> businessUnits;
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.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;
User other = (User) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
Listener Class
#Service
#Slf4j
public class BusinessUnitLoggingService implements LoggingService{
#Autowired
private AuditLogSummerizedRepository repo;
#Override
public void getMessage(AuditLogSummerizedJpaEntity logSummerizedJpaEntity) {
logSummerizedJpaEntity.setMessage(StringUtils.capitalize(StringUtils.capitalize(logSummerizedJpaEntity.getRevisionType().name()) +
" a " + StringUtils.capitalize(logSummerizedJpaEntity.getEntityName()) + " name "
+ logSummerizedJpaEntity.getPropertyName()+" : "+logSummerizedJpaEntity.getState()));
}
#Override
public void logUpdateEvent(PostUpdateEvent event) {
BusinessUnitJpaEntitiy entity = new BusinessUnitJpaEntitiy();
try {
AuditingEntityHolder<BusinessUnitJpaEntitiy> entityHolder = AuditLogUtil.getEntity(event,entity);
StringBuilder stateBuilder = AuditLogUtil.getLogginDetails(event, entityHolder);
String propertyName = AuditLogUtil.getName(event);
AuditLogServiceData modifier = AuditLogUtil.getCurrentModifierDetails();
AuditLogSummerizedJpaEntity preparedLog = AuditLogUtil.prepareLog(event,modifier, propertyName, stateBuilder);
getMessage(preparedLog);
repo.save(preparedLog);
} catch (Exception e) {
log.error("Error ocured while careting audit log for "+event.getEntity().getClass() + " error"+ e);
}
}
#Override
public void logCollectionUpdateEvent(PostCollectionUpdateEvent event) {
try {
PersistentCollection collection = event.getCollection();
collection.getOwner();
String fieldName = collection.getRole().substring(collection.getRole().lastIndexOf(".")+1);
BusinessUnitJpaEntitiy owner = (BusinessUnitJpaEntitiy) collection.getOwner();
AuditLogServiceData currentModifierDetails = AuditLogUtil.getCurrentModifierDetails();
if("businessUsers".equalsIgnoreCase(fieldName)) {
Map storedSnapshot = (HashMap) collection.getStoredSnapshot();
Set<Object> values = (Set<Object>) collection.getValue();
AuditLogSummerizedJpaEntity auditLogSummerizedJpaEntity = AuditLogSummerizedJpaEntity.builder()
.revisionType(AuditLogEventsEnum.UPDATED)
.entityName(AuditLogUtil.sanitizeEntityName(owner.getClass().getSimpleName()))
.propertyName(owner.getName())
.entityId(owner.getId())
.user(currentModifierDetails.getCurrentUser())
.businessUnitId(currentModifierDetails.getBusinessUnitId())
.tenant(currentModifierDetails.getTenant())
.state(AuditLogUtil.getObjectState(fieldName, storedSnapshot, values))
.build();
getMessage(auditLogSummerizedJpaEntity);
repo.save(auditLogSummerizedJpaEntity);
}
}catch (Exception e) {
log.error("error occured : "+e);
}
}
}
Listener registration
public class HibernateListener {
private final EntityManagerFactory entityManagerFactory;
#Autowired
private EntityUpdateListener updateListener;
#Autowired
private CollectionUpdateListener collectionUpdateListener;
#PostConstruct
private void init() {
SessionFactoryImpl sessionFactory = entityManagerFactory.unwrap(SessionFactoryImpl.class);
EventListenerRegistry registry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
registry.getEventListenerGroup(EventType.POST_UPDATE).appendListener(updateListener);
registry.getEventListenerGroup(EventType.POST_COLLECTION_UPDATE).appendListener(collectionUpdateListener);
}
message generation logic
public static String getObjectState(String fieldName, Map storedSnapshot, Set<Object> values) throws IllegalAccessException, InvocationTargetException {
StringBuilder builder = new StringBuilder();
Collection<Object> oldValues = storedSnapshot.values();
if(oldValues.size() > values.size()) {
oldValues.removeAll(values);
for(Object value : oldValues) {
builder.append(" Removed: "+fieldName+" : ");
builder.append(AuditLogUtil.getMappingEntity(value));
}
}else if(oldValues.size() < values.size()) {
values.removeAll(oldValues);
for(Object value : values) {
builder.append(" Added: " + fieldName + " : ");
builder.append(AuditLogUtil.getMappingEntity(value));
}
}
return builder.toString();
}
issue was with oldValues.removeAll(values);
here we remove the list before transaction is completed hence any modification to this will create a new db opearaation
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);
}
}
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<>();
Trying to do a simple select from Java service layer here is my Model:
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
#Entity
#Table(name="PROF_INFO")
public class ProfileInfo {
#EmbeddedId
private ProfileInfoPK profileInfoPK;
#Column(name="RATING", nullable = true )
private Integer rating;
#Column(name="VIEW_DATE", nullable = false )
private java.util.Date viewDate;
#Column(name="CONTACT_DATE", nullable = true )
private java.util.Date contactDate;
#Column(name="REPORTED_DATE", nullable = true )
private java.util.Date reportedDate;
#Column(name="REPORTED_TYPE", nullable = true )
private Integer reportedType;
#Column(name="REPORTED_COMMENT", nullable = true )
private String reportedComment;
public Integer getRating(){
return this.rating;
}
public void setRating(Integer rating){
this.rating = rating;
}
public java.util.Date getViewDate(){
return this.viewDate;
}
public void setViewDate(java.util.Date viewDate){
this.viewDate = viewDate;
}
public java.util.Date getContactDate(){
return this.contactDate;
}
public void setContactDate(java.util.Date contactDate){
this.contactDate = contactDate;
}
public java.util.Date getReportedDate(){
return this.reportedDate;
}
public void setReportedDate(java.util.Date reportedDate){
this.reportedDate = reportedDate;
}
public Integer getReportedType(){
return this.reportedType;
}
public void setReportedType(Integer reportedType){
this.reportedType = reportedType;
}
public String getReportedComment(){
return this.reportedComment;
}
public void setReportedComment(String reportedComment){
this.reportedComment = reportedComment;
}
#Embeddable
public static class ProfileInfoPK implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Column(name="PST_USER_ID", nullable = false )
private Integer pstUserId;
#Column(name="FILE_NAME", nullable = false )
private String fileName;
public Integer getPstUserId() {
return pstUserId;
}
public void setPstUserId(Integer pstUserId) {
this.pstUserId = pstUserId;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((fileName == null) ? 0 : fileName.hashCode());
result = prime * result
+ ((pstUserId == null) ? 0 : pstUserId.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;
ProfileInfoPK other = (ProfileInfoPK) obj;
if (fileName == null) {
if (other.fileName != null)
return false;
} else if (!fileName.equals(other.fileName))
return false;
if (pstUserId == null) {
if (other.pstUserId != null)
return false;
} else if (!pstUserId.equals(other.pstUserId))
return false;
return true;
}
}
public ProfileInfoPK getProfileInfoPK() {
return profileInfoPK;
}
public void setProfileInfoPK(ProfileInfoPK profileInfoPK) {
this.profileInfoPK = profileInfoPK;
}
}
Here is my DAOImpl:
public List<ProfileInfo> getByEntityandFileName(String entityId,
String fileName)throws NoSuchProfileInfoException , SystemException{
Query query = null;
List<ProfileInfo> results = null;
try{
query = sessionFactory.
getCurrentSession().
createQuery("from ProfileInfo where PST_USER_ID = :PST_USER_ID"); //AND FILE_NAME IN (:FILE_NAME)");
query.setParameter("PST_USER_ID", entityId);
//query.setParameterList("FILE_NAME", fileName.split("\\s*,\\s*"));
}catch(Exception ex){
throw new SystemException(ex);
}
if (query != null) {
results = query.list();
}else{
throw new SystemException("Query Null");
}
if (null != results && !results.isEmpty()) {
return results;
} else {
throw new NoSuchProfileInfoException("No Results Returned");
}
}
}
The db has the PK index on PST_USER_ID,FILE_NAME
and a desc
desc PROF_INFO
Name Null Type
---------------- -------- --------------
PST_USER_ID NOT NULL NUMBER(38)
FILE_NAME NOT NULL VARCHAR2(32)
RATING NUMBER(38)
VIEW_DATE NOT NULL DATE
CONTACT_DATE DATE
REPORTED_DATE DATE
REPORTED_TYPE NUMBER
REPORTED_COMMENT VARCHAR2(1000)
All seems straight forward enough however when I try and query back I receive the following error:
org.hibernate.hql.internal.ast.QuerySyntaxException: ProfileInfo is not mapped [from ProfileInfo where PST_USER_ID = :PST_USER_ID]
Not sure what the culprit is but something has gone up the left. Anything look out of place to you guys and girls?
You have mixed pur SQL with HQL. It should be
createQuery("from ProfileInfo where profileInfoPK.pstUserId = :PST_USER_ID");
check the profileInfoPK.pstUserId part.
In HQLs, you can not refer to the table name or its column names. Instead you have to use the mapped class and its properties.
You could check following things:
Can you check Hibernate configuration file for class mapping details ?
Can you could test without parameter then with parameter?
createQuery("from ProfileInfo " );
createQuery("from ProfileInfo pfi where pfi.profileInfoPK.pstUserId = :pstUserID");
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