Hibernate: HQL is not working [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I wrote a SQL query in my hibernate application using where clause and and .
Here is method ,
public List<Comobility> getComobilityByIdComobilityItemsAndIdPatient(int idComobilityItems, int idPatient, Session session) {
Query query = session.createQuery("from Comobility where comobility_items_idcomobility_items= :idComobilityItems and patient_idpatient= :idpatinet");
query.setParameter("idComobilityItems", idComobilityItems);
query.setParameter("idpatinet", idPatient);
List<Comobility> list = query.list();
return list;
}
But this is not working . There is no any exception or error . Actually, there is no any result.
Have any ideas ?

You should try like that
Wrap your method with try catch block. I believe the query has an error then it will enter to catch block
public List<Comobility>getComobilityByIdComobilityItemsAndIdPatient(int idComobilityItems, int idPatient, Session session) {
try {
logger.debug("xxxx")
//do comething
} catch (Exception e) {
e.printStackTrace();
}
}
Make sure your method parameters are not null
Check your list is empty or not.
For checking you can use IDE debugger or put some logs in your method.

You need to check the generated SQL in the log and execute it against database. If query is compiled and no records are returned, means there are no records for the particular criteria.
To generate the SQL by Hibernate, please set property show_sql to true in hibernate configuration.

Related

JDBC delete method seems to not be working in my Spring Boot service [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I'm trying to create a simple JDBC method to delete from my DB, and I'm not sure if I'm going about this the correct way. This is inside one of my services.
Method:
public void deleteLocation(Integer id) {
String DELETE = "DELETE FROM locale WHERE id=?";
namedParameterJdbcTemplate.update(DELETE, new BeanPropertySqlParameterSource(id));
}
I would try changing your update line to
namedParameterJdbcTemplate.update(DELETE, id);.
If you are using spring-boot. Then you should be using spring-data-jpa to manage your database. Jdbc is Hard way of doing this.
If you are using jdbc delete to a specific row use prepared statement. You can refer this:
preparedStatement = connection.prepareStatement("DELETE * from table_name WHERE id= ?");
preparedStatement.setInt(1, id);
return !preparedStatement.execute();

Sql to java JDBC database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a problem with searching a particular contact using part of a name. I know how it would look like in SQL but I cant implement it using Java.
if (rs.getString(nameTable LIKE '%name1%';)
Consider adding the LIKE clause to your SQL query instead of handling it in java code:
try(PreparedStatment ps = con.prepareStatement("SELECT * " +
" FROM Contact WHERE contactName like ?")) {
ps.setString(1, "%name1%");
try(ResultSet rs = ps.executeQuery()) {
while(rs.next()) {
//process your data
}
}
} catch(Exception e) {
//deal with it
}

before insert into mysql database how we will check is there any duplicate value using java [duplicate]

This question already has answers here:
check for duplicate data before insert
(3 answers)
Closed 7 years ago.
I have a registration table. I want to insert data into that table, but before insertion I want to check if any data like email already exists. It will insert, if the data is not same then it will insert.
Well, I think it would be enough to configure a UNIQUE restriction in those columns you don't want to be duplicated. Then you only have to deal with the exception thrown if any unique field already exists in the table.
Another option (worse in performance) may be to execute an SQL statement to ensure your data is unique, but I recommend you the first option for its simplicity and performance.
UNIQUE KEY will help you:
Write your query like this:
CREATE TABLE Registration
(
email varchar(255) UNIQUE,
// comment: other fields here
)
Catch exception in your java code:
try {
ps = con.prepareStatement("insert into registration(email,....) values (?,....)");
//other fields go here
ps.setString(1, email);
ps.execute();
} catch (SQLException e) {
e.printStackTrace();
}

insert jdatechooser from java to database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
How can I insert jdatechooser from java to database? I have used all the solutions of the net but still I can't insert. Please help me.
I'm using eclipse environment.
This is my code:
try {
PreparedStatement stm= (PreparedStatement) con.prepareStatement("INSERT INTO d"+
"(dateEntré)"+
"VALUES(?)");
((PreparedStatement)stm).setDate(1,convertUtilDateToSqlDate(dateChooser.getDate()));
statement.execute();
JOptionPane.showMessageDialog(null,"added");
} catch (Exception e1) {
JOptionPane.showMessageDialog(null,e1.getMessage());
}
Your code example seems to be wrong, and this could just be a typo, but since you've provided no other information with regards to the error, this is all we have to go on...
You create a PreapredStatement called stmt, but then use statement to execute the query.
You should be using the same variable/instance to bind and excute the query. You should probably also use executeUpdate instead of execute, this provides some additional information when the statement is executed about the number of rows that were affected by the update.
try {
PreparedStatement stm= (PreparedStatement) con.prepareStatement("INSERT INTO d (dateEntré) VALUES(?)");
stm.setDate(1,convertUtilDateToSqlDate(dateChooser.getDate()));
int rows = statement.executeUpdate();
if (rows > 0) { // Should be 1
JOptionPane.showMessageDialog(null,"added");
} else {
JOptionPane.showMessageDialog(null,"Update failed for unknown reason");
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(null,e1.getMessage());
e1.printStackTrace();
}
This of course assumes that the database column is a compatible type of java.sql.Date
Take a closer look at JDBC Database Access and Using Prepared Statements for more details.

What's wrong with my SQL update? Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
private void subtractCredit(String accountType){ //subtract credit by 1
String CREDITS = "UPDATE CUSTOMERS SET "+accountType+" = "+accountType+" -1, CREDITSUSED=CREDITSUSED+1 WHERE USERNAME='"+username+"'";
try{
ps=con.prepareStatement(CREDITS);
ps.executeUpdate();
}catch(Exception e){
System.out.println(e);
}
}
public String[] getAccount(String accountType){ //Generate a random account.
accountType = "Select * FROM "+accountType+" ORDER BY RAND()";
String[] arr = new String[2];
try{
ps = con.prepareStatement(accountType);
rs = ps.executeQuery();
if(rs.next()){
arr[0] = rs.getString("USERNAME");
arr[1] = rs.getString("PASSWORD");
subtractCredit(accountType);
}
}catch(Exception e){
System.out.println(e);
}
return arr;
}
Here is the catch exception.
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an
error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near 'Select * FROM
TABLE ORDER BY RAND() = Select * FROM TABLE ORDER BY RAND() -1' at
line 1
PLEASE HELP!
What's wrong with my SQL update?
The problem is not in your SQL update!!
Look at the SQL in the error message:
Select * FROM TABLE ORDER BY RAND()
Questions you should ask yourself:
Does that look anything like the update SQL? Nope!!
And what is missing from the 'select'? There is no table name!
If getAccount() is the method that is responsible for this error, then the cause should be obvious to anyone who bothers to read the code. The value of accountType is wrong. If the code is excactly as you have shown us, accountType must contain the string "TABLE". That is not going to work because TABLE is an SQL reserved word. A table called TABLE is a schema design error, because it leads to SQL syntax errors.
The other possibility is that the code actually says this:
accountType = "Select * FROM TABLE " +
accountType + " ORDER BY RAND()";
If so, the problem is that you have called the method with an empty string as the account type.
When you have fixed that, I want you to focus on a number of other significant problems in your code:
Assembling SQL by string bashing like this:
accountType = "Select * FROM "+accountType+" ORDER BY RAND()";
is potentially dangerous. If the value of accountType can come from user input, an HTTP request parameter, or anything else that is not under your control, then this code is vulnerable to an SQL injection attack.
The normal solution is to use a constant SQL string with ? placeholders, and then inject the actual parameter values using PreparedStatement.setXxxx method calls. Unfortunately, a table name can't be injected that way.
Catching Exception like you are doing is a BAD IDEA. Sure, it catches the SQLException that you are anticipating. The problem is that it also catches a bunch of other exceptions that you may not be anticipating. For example, if the code in the try block had a bug that caused it to throw a NullPointerException ... you would catch that too.
Using System.out.println(e) to output a "diagnostic" is bad:
For an end user, the exception message is opaque an alarming.
For a developer, you really need a stacktrace.
Sending developer diagnostics to standard output is generally a bad idea. Use a logging framework.
Your error recovery is almost certainly wrong. If the SQL query fails, then your getAccount method returns an String[2] containing null strings. If the calling code doesn't test for this, then you are likely to get an NPE when you try to use the (bogus) account details.
The correct thing to do is most likely to throw another exception, or if you don't want to add code to handle this up-stack, then allow the SQLException to propagate by removing the try catch ... and declaring the exception in the method signature.
This is minor, but most people think that updating the value of a method parameter is bad style. You are doing this when you assign a new value to accountType. Better style would be to declare a local variable and use that to hold the SQL string.
Consider this sequence of statements (drawn from two methods, but the variable names correspond):
getAccount("TABLE"); // inferred
accountType = "Select * FROM "+accountType+" ORDER BY RAND()";
String CREDITS = "UPDATE CUSTOMERS SET "+accountType+" = "+accountType
+ " -1, CREDITSUSED=CREDITSUSED+1 WHERE USERNAME='"+username+"'";
ps=con.prepareStatement(CREDITS);
ps.executeUpdate();
The error indeed occurs in your UPDATE statement, but only part of it appears in the message. The sequence of statements above explains how it got that way. In particular, consider the effect of the assignment to accountType on the subsequent statements.

Categories