Hibernate Criteria - sql
I have one class
#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;
// private boolean serviceContract;
#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;
i want to get all MachineSalesReport,then my dao is
Criteria dc = session.createCriteria(MachineSalesReport.class);
dc.setFetchMode("installationInformation", FetchMode.JOIN);
dc.setFetchMode("customerInformation", FetchMode.JOIN);
dc.setFetchMode("internalInformation", FetchMode.JOIN);
dc.setFetchMode("contracts", FetchMode.JOIN);
dc.setMaxResults(1);
But i find the console show the sql is:
Hibernate: select this_.id as id5_4_, this_.avery_sales_order_no as avery2_5_4_,this_.contract_flag as contract3_5_4_, this_.customer_information_id as customer19_5_4_, this_.edit_date as edit4_5_4_, this_.editor as editor5_4_, this_.email_flag as email6_5_4_, this_.exists as exists5_4_, this_.installation_flag as installa8_5_4_, this_.installation_information_id as install20_5_4_, this_.internal_information_id as internal21_5_4_, this_.is_final as is9_5_4_, this_. last_update_editor as column10_5_4_, this_.last_update_date as last11_5_4_, this_.nature_of_sales as nature12_5_4_, this_.product_line as product13_5_4_, this_.program as program5_4_, this_.remarks as remarks5_4_, this_.retailer as retailer5_4_, this_.ship_out_date as ship17_5_4_, this_.supply_agreement as supply18_5_4_, contracts2_.machine_report_id as machine16_5_6_, contracts2_.id as id0_6_, contracts2_.id as id0_0_, contracts2_.contract_from as contract2_0_0_, contracts2_.contract_no as contract3_0_0_, contracts2_.contract_price as contract4_0_0_, contracts2_.contract_to as contract5_0_0_, contracts2_.create_date as create6_0_0_, contracts2_.create_editor as create7_0_0_, contracts2_.is_final as is8_0_0_, contracts2_.last_date as last9_0_0_, contracts2_.last_editor as last10_0_0_, contracts2_.machine_report_id as machine16_0_0_, contracts2_.remark as remark0_0_, contracts2_.service_contract_years as service12_0_0_, contracts2_.service_left_no as service13_0_0_, contracts2_.service_no as service14_0_0_, contracts2_.type as type0_0_, customerin3_.id as id1_1_, customerin3_.bill_to_company_address_cn as bill2_1_1_, customerin3_.bill_to_company_address_en as bill3_1_1_, customerin3_.bill_to_company_name as bill4_1_1_, customerin3_.bill_to_code as bill5_1_1_, customerin3_.bill_to_country as bill6_1_1_, customerin3_.customer_email as customer7_1_1_, customerin3_.customer_fax as customer8_1_1_, customerin3_.customer_phone as customer9_1_1_, customerin3_.customer_name as customer10_1_1_, customerin3_.ship_from as ship11_1_1_, customerin3_.ship_to_company_address_cn as ship12_1_1_, customerin3_.ship_to_company_address_en as ship13_1_1_, customerin3_.ship_to_company_name as ship14_1_1_, installati4_.id as id2_2_, installati4_.customer_email as customer2_2_2_, installati4_.customer_fax as customer3_2_2_, installati4_.customer_name as customer4_2_2_, installati4_.customer_phone as customer5_2_2_, installati4_.factory_address_cn as factory6_2_2_, installati4_.factory_address_en as factory7_2_2_, installati4_.factory_name as factory8_2_2_, internalin5_.id as id3_3_, internalin5_.avery_entity_name as avery2_3_3_, internalin5_.city as city3_3_, internalin5_.country as country3_3_, internalin5_.csr_email as csr5_3_3_, internalin5_.csr_name as csr6_3_3_, internalin5_.csr_phone as csr7_3_3_, internalin5_.salesperson_email as salesper8_3_3_, internalin5_.salesperson_name as salesper9_3_3_, internalin5_.salesperson_phone as salespe10_3_3_ from machine_report this_ left outer join contracts2 contracts2_ on this_.id=contracts2_.machine_report_id left outer join customer_information customerin3_ on this_.customer_information_id=customerin3_.id left outer join installation_information installati4_ on this_.installation_information_id=installati4_.id left outer join internal_information internalin5_ on this_.internal_information_id=internalin5_.id where this_.is_final=? and this_.exists=? order by this_.id desc 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_.customer_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_.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 have so many sql? if i want to set Max(1000),i will get 3000 sql.
I want the first sql,not the all sql.
See below reference
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html#querycriteria-dynamicfetching
setFetchMode will fetch subsequent joins also, use createAlias instead
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html#querycriteria-associations
Related
Nested query in JPQL
I have 2 entities - #Table(name = "MM_MONITORING_CARD") #Entity(name = "mm_MonitoringCard") public class MonitoringCard extends StandardEntity { #ManyToOne(fetch = FetchType.LAZY) #JoinColumn(name = "CLIENT_ID") private Counterparty client; #Column(name = "START_DATE") private LocalDate startDate; #Column(name = "END_DATE") private LocalDate endDate; ...otherColumn } and #DiscriminatorColumn(name = "TYPE", discriminatorType = DiscriminatorType.STRING) #Table(name = "MM_COUNTERPARTY") #Entity(name = "mm_Counterparty") #DiscriminatorValue("COUNTERPARTY") #NamePattern("%s|name") public class Counterparty extends StandardEntity { #Column(name = "TYPE", insertable=false, updateable=false) private String type; ...otherColumn I need get all examples monitoringCard with condition - 1) between start date and end date 2) with Counterparty type = 'someType' I do method - List<MonitoringCard> monitoringCardList = dataManager.load(MonitoringCard.class) .query("select distinct cm from mm_MonitoringCard m join mm_Counterparty cm where (m.current_date between cm.startDate and cm.endDate) and cm.type = :type") .parameter("type", "someType") .list(); but i get error, how can i make a correct request? thanks
Your query is not correct. It should use a join like this: select distinct m.Counterparty from mm_MonitoringCard m where (m.current_date between m.Counterparty.startDate and m.Counterparty.endDate) and m.Counterparty.type = :type In JPA you don't need to do an explicit join when navigating on a ToOne relationship.
Hibernate query exception:cannot dereference scalar collection element
I am getting following error after starting my spring application: Caused by: java.lang.IllegalArgumentException: org.hibernate.QueryException: cannot dereference scalar collection element: metadata_descriptor_id [SELECT d FROM com.org.entity.documents.Document d INNER JOIN d.documentMetadata md ON md.document_id = d.id WHERE (md.metadata_descriptor_id.id NOT IN (:documentMetadataId))] Here is my Document class: #Entity #Table(name = "documents") public class Document { #Id #GeneratedValue(strategy = GenerationType.IDENTITY) #Column(name = "id") private long id; #Column(name = "name", nullable = false, unique = true) private String name; #Column(name = "archived", nullable = false) private boolean archived; #Column(name = "creation_date", nullable = false) private Instant creationDate; #Column(name = "file_text_processing_status", nullable = false) #Enumerated(EnumType.STRING) private FileTextProcessingStatus fileTextProcessingStatus; #ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) #JoinColumn(name = "template_file_id", referencedColumnName = "id") private TemplateFile templateFile; #ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) #JoinColumn(name = "state_descriptor_id", referencedColumnName = "id") private StateDescriptor stateDescriptor; #ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) #JoinColumn(name = "user_id", referencedColumnName = "id") private UserEntity user; #ElementCollection(targetClass = String.class) #Column(name = "tag", nullable = false) #CollectionTable(name = "document_tags", joinColumns = #JoinColumn(name = "document_id")) private Set<String> tags = new HashSet<>(); #ElementCollection #CollectionTable(name = "document_metadata", joinColumns = { #JoinColumn(name = "document_id", referencedColumnName = "id")}) #MapKeyJoinColumn(name = "metadata_descriptor_id", referencedColumnName = "id") #Column(name = "value", nullable = false) private Map<MetadataDescriptor, String> documentMetadata = new HashMap<>(); #OneToMany(mappedBy = "document", cascade = CascadeType.ALL, orphanRemoval = true) private Set<DocumentFileVersion> documentVersions = new HashSet<>();`enter code here` And here is Repository method that fails: #Lock(LockModeType.PESSIMISTIC_WRITE) #Query(value = "SELECT d FROM Document d INNER JOIN d.documentMetadata md ON md.document_id = d.id" + " WHERE (md.metadata_descriptor_id NOT IN (:documentMetadataId))") List<Document> findAllByDocumentRequiredMetadataNotSet(long documentMetadataId); I have seen an answer for similar question here: getting Caused by: org.hibernate.QueryException: cannot dereference scalar collection element: roles But it's not helpful in my case. I will be very glad for any suggestions.
The type of md is String this is why you see an error. What you need is something like this: #Lock(LockModeType.PESSIMISTIC_WRITE) #Query(value = "SELECT d FROM Document d INNER JOIN d.documentMetadata md WHERE (KEY(md).id NOT IN (:documentMetadataId))") List<Document> findAllByDocumentRequiredMetadataNotSet(long documentMetadataId); You also had a ON clause which is no necessary/wrong. I think you should read into HQL/JPQL first as you don't seem to understand that a join of an association, will add the join predicate in the SQL automatically. Note though, that the syntax KEY(..).id is only supported in newer Hibernate versions, so you might have to update.
How to convert my native SQL query into a JPQL query
I'm trying to convert a native SQL query into a JPQL query. Presented first are the JPA entities and the repository interface: LearnerActivity #Entity #Table(name = "learner_activity") public class LearnerActivity implements Serializable { #Id #GeneratedValue(strategy = GenerationType.AUTO) private Long id; #ManyToMany #JoinTable(name = "learner_activity_unit", joinColumns = #JoinColumn(name="learner_activitys_id", referencedColumnName="ID"), inverseJoinColumns = #JoinColumn(name="units_id", referencedColumnName="ID")) private Set<Unit> units = new HashSet<>(); #ManyToMany #Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) #JoinTable(name = "learner_activity_performance_criteria", joinColumns = #JoinColumn(name="learner_activitys_id", referencedColumnName="ID"), inverseJoinColumns = #JoinColumn(name="performance_criterias_id", referencedColumnName="ID")) private Set<PerformanceCriteria> performanceCriterias = new HashSet<>(); } LearnerJobOnSiteChecklistSectionItem #Entity #Table(name = "learner_job_on_site_checklist_section_item") public class LearnerJobOnSiteChecklistSectionItem implements Serializable { #Id #GeneratedValue(strategy = GenerationType.AUTO) private Long id; #ManyToOne #JoinColumn(name = "learner_activity_id") private LearnerActivity learnerActivity; } LearnerPortfolioPerformanceCriteriaAchievement #Entity #Table(name = "learner_portfolio_performance_criteria_achievement") public class LearnerPortfolioPerformanceCriteriaAchievement implements Serializable { #Id #GeneratedValue(strategy = GenerationType.AUTO) private Long id; #ManyToOne #JoinColumn(name = "performance_criteria_id") private PerformanceCriteria performanceCriteria; #ManyToMany #Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) #JoinTable(name = "learner_portfolio_performance_criteria_achievement_learner_job_on_site_checklist_section_item", joinColumns = #JoinColumn(name="learner_portfolio_performance_criteria_achievements_id", referencedColumnName="ID"), inverseJoinColumns = #JoinColumn(name="learner_job_on_site_checklist_section_items_id", referencedColumnName="ID")) private Set<LearnerJobOnSiteChecklistSectionItem> learnerJobOnSiteChecklistSectionItems = new HashSet<>(); } I'm looking to get all LearnerPortfolioPerformanceCriteriaAchievements which have the same PerformanceCriteria as a given LearnerJobOnSiteChecklistSectionItem's Activity. LearnerPortfolioPerformanceCriteriaAchievementRepository public interface LearnerPortfolioPerformanceCriteriaAchievementRepository extends JpaRepository<LearnerPortfolioPerformanceCriteriaAchievement,Long> { #Query("select distinct lppca from LearnerJobOnSiteChecklistSectionItem si inner join si.learnerActivity la inner join LearnerPortfolioPerformanceCriteriaAchievement lppca where lppca.performanceCriteria member of la.performanceCriterias and si.id =:sectionItemId") public List<LearnerPortfolioPerformanceCriteriaAchievement> findForSectionItem(#Param("sectionItemId") Long sectionItemId); } Native SQL SELECT a.id FROM learner_job_on_site_checklist_section_item AS i JOIN learner_activity_performance_criteria AS c ON c.learned_activitys_id = i.learned_activitys_id INNER JOIN learner_portfolio_performance_criteria_achievement AS a ON a.performance_criteria_id = c.performance_criterias_id where i.id = 2 Understanding that I can replace my SQL ON with WHERE clauses, my best JPQL attempt so far is this: SELECT DISTINCT lppca FROM LearnerJobOnSiteChecklistSectionItem si INNER JOIN si.learnerActivity la INNER JOIN LearnerPortfolioPerformanceCriteriaAchievement lppca WHERE lppca.performanceCriteria MEMBER OF la.performanceCriterias AND si.id =:sectionItemId However, running this JPQL throws the following exception: Caused by: java.lang.IllegalStateException: No data type for node: org.hibernate.hql.internal.ast.tree.IdentNode \-[IDENT] IdentNode: 'lppca' {originalText=lppca}
The following query will work: SELECT a FROM LearnerPortfolioPerformanceCriteriaAchievement a , LearnerActivity v , LearnerJobOnSiteChecklistSectionItem i WHERE i.id = :sectionItemId AND i.learnerActivity = v AND a.performanceCriteria MEMBER OF v.performanceCriterias AND i MEMBER OF a.learnerJobOnSiteChecklistSectionItems Have created a sample application to test the query (I have used shorter and simpler class names to make it easy to read).
Inheritance JPA 2.1
I got this entities: #Entity #Table(name = "PROCESS_VERSION") public class ProcessVersion implements Serializable { private static final long serialVersionUID = 1L; private static final String SEQ_NAME = "PROCESS_VERSION_id_SEQ"; #Id #Basic(optional = false) #NotNull #SequenceGenerator(name = "seq", sequenceName = SEQ_NAME, allocationSize = 1) #GeneratedValue(generator = "seq", strategy = GenerationType.SEQUENCE) #Column(name = "ID") private BigDecimal id; #OneToMany(mappedBy = "idProcessVersion", cascade = CascadeType.ALL) private List<Stage> stageList; #OneToMany(mappedBy = "idProcessVersion", cascade = CascadeType.ALL) private List<Kpi> kpiList; //Getters and Setters } #Entity #Table(name = "KPI") #Inheritance(strategy=InheritanceType.JOINED) #DiscriminatorColumn( name="ID_CATEGORY", discriminatorType=DiscriminatorType.INTEGER) public class Kpi implements Serializable { private static final long serialVersionUID = 1L; private static final String SEQ_NAME = "KPI_id_SEQ"; #Id #Basic(optional = false) #NotNull #SequenceGenerator(name = "seq", sequenceName = SEQ_NAME, allocationSize = 1) #GeneratedValue(generator = "seq", strategy = GenerationType.SEQUENCE) #Column(name = "ID") private BigDecimal id; #JoinColumn(name = "ID_PROCESS_VERSION", referencedColumnName = "ID") #ManyToOne(optional = false) private ProcessVersion idProcessVersion; #JoinColumn(name = "ID_CATEGORY", referencedColumnName = "ID", insertable = false, updatable = false) #ManyToOne(optional = false) private KpiCategory idCategory; //Getters and Setters } #Entity #Table(name = "KPI_TEMPORARY") #DiscriminatorValue("1") public class KpiTemporary extends Kpi implements Serializable { private static final long serialVersionUID = 1L; #JoinColumn(name = "ID_STAGE_SOURCE", referencedColumnName = "ID") #ManyToOne(optional = false) private Stage idStageSource; #JoinColumn(name = "ID_STAGE_TARGET", referencedColumnName = "ID") #ManyToOne(optional = false) private Stage idStageTarget; //Getters and Setters } #Entity #Table(name = "KPI_COUNTER") #Inheritance(strategy=InheritanceType.JOINED) #DiscriminatorValue(KpiCategory.CATEGORY_COUNTER) public class KpiCounter extends Kpi implements Serializable { private static final long serialVersionUID = 1L; #JoinColumn(name = "ID_STAGE", referencedColumnName = "ID") #ManyToOne(optional = false) private Stage idStage; //Getters and Setters } When I try to get the kpis list from ProcessVersion I always get 0. I check the sql generated by hibernate and I see this sentece wich is very strage: select kpilist0_.ID_PROCESS_VERSION as ID_PROCESS_VERSION5_14_0_, kpilist0_.ID as ID2_5_0_, kpilist0_.ID as ID2_5_1_, kpilist0_.DESCRIPTION as DESCRIPTION3_5_1_, kpilist0_.ID_CATEGORY as ID_CATEGORY1_5_1_, kpilist0_.ID_PROCESS_VERSION as ID_PROCESS_VERSION5_5_1_, kpilist0_.NAME as NAME4_5_1_, kpilist0_2_.ID_STAGE as ID_STAGE2_7_1_, kpilist0_3_.ID_STAGE_SOURCE as ID_STAGE_SOURCE2_9_1_, kpilist0_3_.ID_STAGE_TARGET as ID_STAGE_TARGET3_9_1_, kpicategor1_.ID as ID1_6_2_, kpicategor1_.NAME as NAME2_6_2_, stage2_.ID as ID1_15_3_, stage2_.DESCRIPTION as DESCRIPTION2_15_3_, stage2_.ID_PROCESS_VERSION as ID_PROCESS_VERSION5_15_3_, stage2_.ID_RESPONSABLY as ID_RESPONSABLY6_15_3_, stage2_.ID_STAGE as ID_STAGE3_15_3_, stage2_.NAME as NAME4_15_3_, processver3_.ID as ID1_14_4_, stage10_.ID as ID1_15_11_, stage10_.DESCRIPTION as DESCRIPTION2_15_11_, stage10_.ID_PROCESS_VERSION as ID_PROCESS_VERSION5_15_11_, stage10_.ID_RESPONSABLY as ID_RESPONSABLY6_15_11_, stage10_.ID_STAGE as ID_STAGE3_15_11_, stage10_.NAME as NAME4_15_11_, stage11_.ID as ID1_15_12_, stage11_.DESCRIPTION as DESCRIPTION2_15_12_, stage11_.ID_PROCESS_VERSION as ID_PROCESS_VERSION5_15_12_, stage11_.ID_RESPONSABLY as ID_RESPONSABLY6_15_12_, stage11_.ID_STAGE as ID_STAGE3_15_12_, stage11_.NAME as NAME4_15_12_ from KPI kpilist0_ left outer join KPI_COUNTER kpilist0_2_ on kpilist0_.ID=kpilist0_2_.ID left outer join KPI_TEMPORARY kpilist0_3_ on kpilist0_.ID=kpilist0_3_.ID inner join KPI_CATEGORY kpicategor1_ on kpilist0_.ID_CATEGORY=kpicategor1_.ID inner join STAGE stage2_ on kpilist0_3_.ID_STAGE_SOURCE=stage2_.ID left outer join PROCESS_VERSION processver3_ on stage2_.ID_PROCESS_VERSION=processver3_.ID inner join STAGE stage10_ on kpilist0_3_.ID_STAGE_TARGET=stage10_.ID inner join STAGE stage11_ on kpilist0_2_.ID_STAGE=stage11_.ID where kpilist0_.ID_PROCESS_VERSION=?; The question is why the sentece has 3 inner with stage..Two from KpiTemporary and One from KpiCounter the problem is this will never have the 3 values because the kpi is temporary or is counter but not both. Can anyone tell me something about?. Is there any extra config to apply. I am using JPA 2.1 specification with hinerbate 4.3.5.Final
The problem is that you have 3 mappings of: #ManyToOne(optional = false) On both counter and temporary. The false means that the mapping is 1..M -> 1, while true would mean the mapping is 0..M ->1, I think you would want the latter. Change those to true and see if you get the sql you desire.
java.lang.IllegalArgumentException with toplink and JPA
I've a problem with JPA, whenever execute this query #NamedQuery(name = "Usuario.getUsuarioIntento", query = "SELECT u.intentos_id FROM Usuario u WHERE u.username = :username and u.borrado = 0") i get this error: java.lang.IllegalArgumentException: NamedQuery of name: Usuario.getUsuarioIntento not found. But if i execute this query #NamedQuery(name = "Usuario.getUsuarioIntento", query = "SELECT u.id FROM Usuario u WHERE u.username = :username and u.borrado = 0") Work fine,Why? My table,Usuario: MY USER TABLE i try with other column as 'superusuario','version_jpa' and doesn't work, the only columns that work fine are 'id,'borrado' and 'username' Class Usuario: #Temporal(TemporalType.TIMESTAMP) private Date fechaCreacion; #Id #GeneratedValue (strategy=GenerationType.AUTO) private int id; #OneToOne(cascade = CascadeType.ALL) private Password password; #OneToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH}, fetch = FetchType.LAZY) private List<Password> clavesAntiguas; #OneToOne private Persona persona; private String sessionId; private String username; #ManyToOne(cascade = CascadeType.REFRESH) private Rol rol; #ManyToOne(cascade = CascadeType.REFRESH) private Perfil perfil; #OneToOne (cascade = CascadeType.ALL) private IntentosBloqueo intentos; private boolean superUsuario; private int borrado; private int esManager; #OneToMany ( cascade = {CascadeType.ALL} , fetch = FetchType.LAZY) private Collection<UsuarioSociedad> sociedades; #OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.REFRESH) #JoinTable (name="USR_UND_VIS", joinColumns={ #JoinColumn (name="ID_USU", table="USUARIO", referencedColumnName="ID"), }, inverseJoinColumns= #JoinColumn (name="ID_UNI", table="UND_ORG", referencedColumnName="ID") ) private List<UnidadOrganizativa> unidadesVisibles; #OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.REFRESH) #JoinTable (name="USR_UND_DIS", joinColumns={ #JoinColumn (name="ID_USU", table="USUARIO", referencedColumnName="ID"), }, inverseJoinColumns= #JoinColumn (name="ID_UNI", table="UND_ORG", referencedColumnName="ID") ) private List<UnidadOrganizativa> unidadesDisponibles;
Because Named query works on Entity objetc not on datbase column. You try to find another entity object which contains that id. In That case your named query will give you the object of that entity class and from that object u can get the id or whtever fiels of that entity. JPA named query is not like SQL or oracle query. Iin in DB your column name is xyz but in entity your column name is ABC then you have to fetch ABC in named query not XYZ.