How can I run this SQL statement with SpringBoot data JPA? - java

I'm trying to create a data filter using SpringBoot and PostgreSQL, I'm trying to run a query to get a customer by its name or id or account id in a searchBar, running into an issue when running a native SQL statement in Spring Data JPA, I'm getting the following error:
The error says that Could not execute query. I've tried running the statement in different ways but still giving me the error, these are the ways I have tried:
#Query(
value = "SELECT json_data FROM contact WHERE name = :searchText OR account_id = :searchText OR id = :searchText",
nativeQuery = true)
#Query(
value = "SELECT json_data FROM contact WHERE contact.name LIKE %:searchText% OR contact.account_id LIKE %:searchText% OR contact.id LIKE %:searchText%",
nativeQuery = true)
#Query(
value = "SELECT json_data FROM contact WHERE name = ?1 OR account_id = ?1 OR id = ?1",
nativeQuery = true)
Page<Contact> findByWord(Pageable pageable, #Param("searchText") String searchText);
I'm able to run successfully the query in PGAdmin as follows:
SELECT json_data FROM contact
WHERE name = 'TESLA ARQUITECTURA S.A.S'
OR account_id = ''
OR id = ''
or:
SELECT json_data FROM contact
WHERE name = ''
OR contact.account_id = ''
OR contact.id = '2'
or:
SELECT json_data FROM contact
WHERE name = ''
OR account_id = '1674590687S'
OR id = ''
All of these statements are working and the idea is that if I pass as a parameter to the SQL statement it will return the information from the column json_data.
So I'm not sure if im doing something wrong when creating the query in the repository, I would appreciate so much your help on this.

Do select * not select json_data in your query, currently you are trying to map a single column into a whole Entity that's why it's complaining the id is missing from the result set. column name seq_id was not found in this result set was there in the error log all along.

Related

SQL Syntax error in Hibernate's map function

SELECT NEW Map (PRODUCT_CATEGORY, COUNT(PRODUCT_CATEGORY) AS COUNTER) from Product WHERE USER_ID = (SELECT USER_ID FROM USERS WHERE USERNAME='burak123'
Hi everyone,
As hibernates document says here: https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-select
I am trying to map the query result into a hash map like this
#Query(value = "SELECT NEW Map( PRODUCT_CATEGORY , COUNT(PRODUCT_CATEGORY) AS COUNTER ) from Product WHERE USER_ID=(SELECT USER_ID FROM USERS WHERE USERNAME=(:username)) ",nativeQuery = true)
HashMap<Integer,Integer> getCategoryCountsWithUsername(#Param("username")String username);
But it throws an JdbcSyntaxErrorException. I am trying to solve this for like 1 hours already. Can someone help?
You are using a native query, not an HQL query. Check your SQL syntax.
With a native query, your named parameter won't work. You need to remove the nativeQuery = true

Filter JSON column from MySQL table in spring boot

Below is my query to filter the json column in MySQL table ,
public interface MpaCustomizationRepository extends
JpaRepository<MpaCustomization, Serializable> {
#Query(nativeQuery = true, value = "select * from MPA_CUSTOMIZATION where json_contains(domain_based_properties, '{\"id\" : ?1}')")
MpaCustomization findByDomainBaseId(String domainId);
}
above method throws below SQL error,
but if I hard code the variable and run the query like below its works fine,
#Query(nativeQuery = true, value = "select * from MPA_CUSTOMIZATION where json_contains(domain_based_properties, '{\"id\" : 2}')")
MpaCustomization findByDomainBaseId(String domainId);
How to fix this issue?
Use $.id for values when using native query, as SQL accepts like it only.
Other way, you may use :id and bind parameter {\"id\":\"" + <value> + "\"} to the query.
Maybe the following will work.
#Query(nativeQuery = true, value = "select * from MPA_CUSTOMIZATION where json_contains(domain_based_properties, ?1 , '$.id'")
MpaCustomization findByDomainBaseId(String domainId);
Source

Bind parameter to a native query annotation JPA

I have the following piece of code:
#Query(value = "select * from james_mail where encode(header_bytes, 'escape') like '%Message-ID: :messageId%'", nativeQuery = true)
List<JamesMail> findByMessageIdFromHeader(#Param(value = "messageId") String messageId);
The expected behavior is to execute the query with bind parameter (e.g. messageID)
Actual behavior is that the query is executed as it is, without biding
What is the solution for actually biding, or there is an workaround for my problem?
Technology stack:
Spring Boot, JPA, Hibernate
here you are trying to encode header_bytes which is contained table james_mail right
and you want to find rows which contains value matching to messageId and contains Message-ID
#Query(value = "select * from james_mail where encode(header_bytes, 'escape') like '%Message-ID%' and encode(header_bytes, 'escape') like %:messageId%", nativeQuery = true)
List<JamesMail> findByMessageIdFromHeader(#Param(value = "messageId") String messageId);
Try to correct your query in this way:
#Query(value = "select * from james_mail where encode(header_bytes, 'escape') like '%Message-ID: ' || :messageId || '%'", nativeQuery = true)
List<JamesMail> findByMessageIdFromHeader(#Param(value = "messageId") String messageId);

Passing a mysql query to the database using a java program

I am new to mysql and I am trying to connect to the database using a Java Program and I am passing a mysql query.
public class dbconnect {
public static void main(String[] args) throws SQLException,ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn =DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase?user=root&password=root");
Statement st = conn.createStatement();
int custid= 0;
String myname = null;
String query = "select name from groups where customer_id = 2;";
//This query has a problem can anyone help me fix it.
System.out.println(query);
ResultSet rs1 = st.executeQuery(query);
System.out.println("after query");
while (rs1.next()){
custid = rs1.getInt("customer_id");
myname = rs1.getString("name");
System.out.println(myname);
System.out.println(custid);
}
}
}
I am passing a query "select name from groups where customer_id = 2" .
Here "name" is a coloumn,"groups" is a table and "customer_id" is another column. In the program when I give this query(no typos) I get the following error
Exception in thread "main" java.sql.SQLException: Column 'customer_id' not found.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1144)
at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2815)
at com.memoir.client.widgets.memogen.dbconnect.main(dbconnect.java:61)
I have checked with the table , customer_id is present in the table . They are no spelling mistakes also .Even then it says that customer_id column is not found .
Can anyone help me fix it.
The query needs to be:
String query = "select name, customer_id from groups where customer_id = 2;";
Honestly it doesn't make any sense, your query is
String query = "select name from groups where customer_id = 2;";
and you expect to get customer_id ??
as you are already passing customer_id in where clause you don't need to get it back again from db.
String query = "select customer_id,name from groups where customer_id = 2;";
The above would work with your current code .
You are accessing only name column in query and you are try to get "customer_id" in while loop from result set
while (rs1.next()){
custid = rs1.getInt("customer_id"); // **error is here - remove this line or change your query**
myname = rs1.getString("name");
System.out.println(myname);
System.out.println(custid);
}
Your problem is that you are trying to get an invalid column ("cutomer_id") from the result set which contains only the "name" column.
To resolve this you have to select also the "customer_id" in your query:
"select name, customer_id from groups where customer_id = 2";
custid = rs1.getInt("customer_id");
you result set does not have customer_id
Include that too in your query
try this
String mysqlquery = "select name, customer_id from groups where customer_id=2";

Query using alias on column give an error

When i use alias for column i get error. Without alias everytinig works good. What is the problem with that ? This is simple example, but need to use more aliases in real project to wrap results in some not-entity class, but can't because of this error. How to solve this ?
NOT WORKING (with alias on id column):
public List<Long> findAll(Long ownerId) {
String sql = "select id as myId from products where ownerId = "+ownerId;
SQLQuery query = getSession().createSQLQuery(sql);
return query.list();
}
Error:
WARN [JDBCExceptionReporter:77] : SQL Error: 0, SQLState: S0022 ERROR
[JDBCExceptionReporter:78] : Column 'id' not found.
WORKING (without alias):
public List<Long> findAll(Long ownerId) {
String sql = "select id from products where ownerId = "+ownerId;
SQLQuery query = getSession().createSQLQuery(sql);
return query.list();
}
If your "product" is mapped, hibernate probably don't know about "myId" and therefore can't select it.
You can try something like:
getSession().createSQLQuery(sql).addScalar("myId", Hibernate.LONG)

Categories

Resources