jdbc.SQLServerException on group by clause - java

While executing this code in my project:
Integer countObj = (Integer) ht.findByCriteria(criteria.setProjection(Projections.rowCount())).get(0);
I get the following exception:
com.microsoft.sqlserver.jdbc.SQLServerException: Column "PRODUCT_TASK.PRODUCT_TASK_ID" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause."
Here I am using two tables.
Product_task with product_task_id as primary key
Product_info with product_info_id as primary key
product_info_id is the foreign key for Product_task.
By executing that query I will get count.
I am getting this SQL query in my logs:
select count(*) as Count from PRODUCT_TASK pt inner join
PRODUCT_INFO pin on pt.PRODUCT_INFO_ID=pin.PRODUCT_INFO_ID
where pin.UPC like ? order by pt.PRODUCT_TASK_ID asc**
I know how to change SQL query (group by clause need to be there) but I don't know how to modify the Hibernate query in order to get the result.

You just need to use Projections's .groupProperty() method in your Criteria.
groupProperty
public static PropertyProjection groupProperty(String propertyName)
A grouping property value
Your code would be like this:
Integer countObj = (Integer) ht.findByCriteria(criteria.setProjection(Projections.rowCount()
.add(Projections.groupProperty("product_task_id"))))
.get(0);

Related

JPA Update Multiple Records in Table for a ID

I have a requirement for a Input record with id1 from source, in target table I need to update value v1 in column c1 and in target for id1 there are multiple records. Using JPA I need to update all those records with value v1. Using JPA what is the best way to do this?
I used below
findallbyid() then saveall() - it failed saying there are mutliple records in target but expected was one.
Based on the details provided findallbyid() then saveall()
here the method findallbyid() is actually expecting to find only one record in the table, where as there are multiple rows.
changing the to signature of the method should work as expected without expection. As it expect capitalised words in method signature
https://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/JpaRepository.html
List<T> findAllById(Long id);
but recommend not to read all rows and then save again just to update a column or two, you could use something like below to achieve the same
#Modifying
#Transactional
#Query(value = "UPDATE table t SET t.column = :status WHERE t.id = :id")
int update(#Param("status") String status, #Param("id") Long id);

Merge and When Matched query giving an error sql server

I have a query which I am trying to test. The query should update the data if it finds data in the table with existing primary key. If it doesn't then insert into the table.
The Primary key is of type int and in the properties I can see Identity is set to "True" which I assume it means that it will automatically set the new id for the primary if it is inserted.
MERGE INTO Test_table t
USING (SELECT 461232 ID,'Test1-data' Fascia FROM Test_table) s
ON (t.ID = s.ID)
WHEN MATCHED THEN
UPDATE SET t.Fascia = s.Fascia
WHEN NOT MATCHED THEN
INSERT (Fascia)
VALUES (s.Fascia);
The issue here is this query doesn't work and it never inserts the data or updates. Also, query gets compiled and I don't get any compilation error
Also the reason I want this query is to work because then I will use Java prepared statement to query the database so I am assuming I can do
SELECT ? ID,? Fascia FROM Test_table
So that I can pass the values with set methods in java.
Please let me know if there is something wrong in my query.
You are selecting from the target table as your source.
You either need to remove your FROM Test_table or have at least 1 row in Test_table prior to your merge.
rextester demo: http://rextester.com/XROJD28508
MERGE INTO Test_table t
USING (SELECT 461232 ID,'Test1-data' Fascia --FROM Test_table
) s
ON (t.ID = s.ID)
WHEN MATCHED THEN
UPDATE SET t.Fascia = s.Fascia
WHEN NOT MATCHED THEN
INSERT (Fascia)
VALUES (s.Fascia);

jOOQ and bridge tables

I'm trying to imagine how to use jOOQ with bridge tables.
Suppose you have
CREATE TABLE TableA (
id BIGSERIAL PRIMARY KEY
)
CREATE TABLE TableB (
id BIGSERIAL PRIMARY KEY
)
CREATE TABLE TableBridge (
id BIGSERIAL,
table_a_id INTEGER NOT NULL,
table_b_id INTEGER NOT NULL,
CONSTRAINT tablea_pk_id PRIMARY KEY (table_a_id)
REFERENCES TableA (id) MATCH SIMPLE,
CONSTRAINT tableb_pk_id PRIMARY KEY (table_b_id)
REFERENCES TableB (id) MATCH SIMPLE
)
When mapping this schema using jOOQ there will be three record classes, TableARecord, TableBRecord and TableBridgeRecord.
If I want to persist through an insert a record for TableA, should I simply first create and persist the TableB records, then persit rows for TableB and then manually add the TableBridge rows? Isn't there any way to automatically save also the rows in the bridge table?
There are several ways to solve this kind of problem:
1. Do it with a "single" jOOQ statement (running three SQL statements)
The most idiomatic way to solve this kind of problem with standard jOOQ would be to write a single SQL statement that takes care of all three insertions in one go:
ctx.insertInto(TABLE_BRIDGE)
.columns(TABLE_BRIDGE.TABLE_A_ID, TABLE_BRIDGE.TABLE_B_ID)
.values(
ctx.insertInto(TABLE_A)
.columns(TABLE_A.VAL)
.values(aVal)
.returning(TABLE_A.ID)
.fetchOne()
.get(TABLE_A.ID),
ctx.insertInto(TABLE_B)
.columns(TABLE_B.VAL)
.values(bVal)
.returning(TABLE_B.ID)
.fetchOne()
.get(TABLE_B.ID)
)
.execute();
The above works with jOOQ 3.8. Quite possibly, future versions will remove some of the verbosity around returning() .. fetchOne() .. get().
2. Do it with a single SQL statement
I assume you're using PostgreSQL from your BIGSERIAL data type usage, so the following SQL statement might be an option to you as well:
WITH
new_a(id) AS (INSERT INTO table_a (val) VALUES (:aVal) RETURNING id),
new_b(id) AS (INSERT INTO table_b (val) VALUES (:bVal) RETURNING id)
INSERT INTO table_bridge (table_a_id, table_b_id)
SELECT new_a.id, new_b.id
FROM new_a, new_b
The above query is currently not supported entirely via jOOQ 3.8 API, but you can work around the jOOQ API's limitations by using some plain SQL:
ctx.execute(
"WITH "
+ " new_a(id) AS ({0}), "
+ " new_b(id) AS ({1}) "
+ "{2}",
// {0}
insertInto(TABLE_A)
.columns(TABLE_A.VAL)
.values(aVal)
.returning(TABLE_A.ID),
// {1}
insertInto(TABLE_B)
.columns(TABLE_B.VAL)
.values(bVal)
.returning(TABLE_B.ID),
// {2}
insertInto(TABLE_BRIDGE)
.columns(TABLE_BRIDGE.TABLE_A_ID, TABLE_BRIDGE.TABLE_B_ID)
.select(
select(field("new_a.id", Long.class), field("new_b.id", Long.class))
.from("new_a, new_b")
)
);
Clearly also here, there will be improvements in future jOOQ APIs.
3. Do it with UpdatableRecords
In this particular simple case, you could get away simply by calling:
TableARecord a = ctx.newRecord(TABLE_A);
a.setVal(aVal);
a.store();
TableBRecord b = ctx.newRecord(TABLE_B);
b.setVal(bVal);
b.store();
TableBridgeRecord bridge = ctx.newRecord(TABLE_BRIDGE);
bridge.setTableAId(a.getId());
bridge.setTableBId(b.getId());
bridge.store();

"Invalid Column id" error when counting unique value in Java

I am using the following sql query in my java program:
SELECT COUNT(*) FROM event WHERE externaleventid ='1256294';
But I have an error as:
Invalid Column id.
Same query works fine in SQL Developer.
For some reason you are attempting to get a column named "externaleventid" from the query, but only "count(*)" is available. You shouldn't try to get back the where clause bind variables from the result set, you should get the actual data back from the result set, by column index or by column name.
Try rs.getInt(1) to get the data from the first column. Or, you can alias the column in the query, e.g. SELECT count(*) cnt FROM..., and you can refer to it by the aliased column name: rs.getInt("cnt").

Hibernate issue - Invalid column name

I have added two columns in the sql to get the values through hibernate.My databse is oracle and those fields datatype i number. So i have created the beans with long and (tried Integer too) but when retrieving the values(executing the valuesquery).
Its giving me an error
org.hibernate.type.LongType - could not read column value from result set
java.sql.SQLException: Invalid column name
at oracle.jdbc.driver.OracleStatement.getColumnIndex(OracleStatement.java:3711)
at oracle.jdbc.driver.OracleResultSetImpl.findColumn(OracleResultSetImpl.java:2806)
at oracle.jdbc.driver.OracleResultSet.getLong(OracleResultSet.java:444)
at weblogic.jdbc.wrapper.ResultSet_oracle_jdbc_driver_OracleResultSetImpl.getLong(Unknown Source)
at org.hibernate.type.LongType.get(LongType.java:28)
at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:163)
at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:189)
tABLE DEFINITION :
CREATE TABLE "PRODUCTLIST"
(
PRICELIST_PUBLISH_KEY decimal(22) NOT NULL,
PRODUCT_NBR varchar2(54) NOT NULL,
PRODUCT_KEY decimal(22),
PRODUCT_DESCRIPTION varchar2(360),
PRODUCT_FAMILY_NBR varchar2(30),
PRODUCT_FAMILY_DESCR varchar2(180),
PRODUCT_GROUP_NBR varchar2(30),
PRODUCT_GROUP_DESCR varchar2(180),
PRODUCT_LINE_NBR varchar2(30),
PRODUCT_LINE_DESCR varchar2(180),
PRODUCT_CLASS_CODE varchar2(6),
LAST_PP_GENERATED_DATE_KEY decimal(22),
LAST_PP_GENERATED_DATE date,
PUBLISH_PERIOD_KEY decimal(22) NOT NULL,
PUBLISH_PERIOD_DATE date,
PL_KEY decimal(22),
PRODUCTLIST varchar2(750),
SALES_KEY decimal(22),
PRODUCT varchar2(60),
DM_EXTRACTED_BY_USER varchar2(90)
)
sql :
Query query = session.createSQLQuery(channelQuery)
.addScalar("PRODUCT",Hibernate.STRING)
.addScalar("PRODUCTLIST",Hibernate.STRING)
.addScalar("PRODUCTKEY",Hibernate.LONG)
.addScalar("SALESKEY",Hibernate.LONG)
.setResultTransformer(Transformers.aliasToBean(SearchResult.class));
return query.list();
}
});
Please help me to fix the issue ?
In your table definition, I can't see all the fields you're using in the addScalar() methods: there are no PRODUCTKEY nor SALESKEY fields. Instead I can see a PRODUCT_KEY and a SALES_KEY fields (underscores). I think you should use the correct name of the fields in the addScalar() methods.
But if your query is the one you put in your comments, you have to correct some details:
you should use p instead of pub as alias for the table name. As there is only one table in the query, you can suppress the alias.
In your SELECT clause, p.productprice is not an existing field in your table. Maybe you want to use p.pricelist instead.
In your WHERE clause, p.productnbr is not an existing field in your table. You should use p.product_nbr instead.
Then you should change the field names in the addScalar() methods to match those you are using in the query.
Modified query
SELECT distinct p.product, p.productlist, p.PL_KEY, p.SALES_KEY
FROM productlist p
WHERE p.product_nbr in ('1002102')
Your code should be:
Query query = session.createSQLQuery(channelQuery)
.addScalar("PRODUCT",Hibernate.STRING)
.addScalar("PRODUCTLIST",Hibernate.STRING)
.addScalar("PL_KEY",Hibernate.LONG)
.addScalar("SALES_KEY",Hibernate.LONG)
.setResultTransformer(Transformers.aliasToBean(SearchResult.class));
return query.list();
If you define aliases in your query, then you can use the alias names instead of the field names. For example, with this query:
SELECT distinct p.product, p.productlist, p.PL_KEY as PRODUCTKEY, p.SALES_KEY as SALESKEY
FROM productlist p
WHERE p.product_nbr in ('1002102')
you can use the following code (it's your original code):
Query query = session.createSQLQuery(channelQuery)
.addScalar("PRODUCT",Hibernate.STRING)
.addScalar("PRODUCTLIST",Hibernate.STRING)
.addScalar("PRODUCTKEY",Hibernate.LONG)
.addScalar("SALESKEY",Hibernate.LONG)
.setResultTransformer(Transformers.aliasToBean(SearchResult.class));
return query.list();

Categories

Resources