Related
I have two entities:
public class Field {
private String inputType;
#OneToMany(cascade = CascadeType.ALL,
fetch = FetchType.LAZY,
mappedBy = "field")
#OrderBy("order_by")
private List<SelectItem> selectItems;
}
public class SelectItem {
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "field_id", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
private Field field;
private int orderBy;
}
It seems that Hibernate is ignoring the #OrderBy annotation in the Field class when selecting the SelectItems associated with a Field instance. I know this because 1) the ordering is not according to the orderBy value and 2) when I intentionally misspell the value in the #OrderBy annotation, everything still works.
In fact, I don't even see evidence in the log that Hibernate is even selecting from the select_items table. Something must be because when I look at the values being returned from the repository, the SelectItems are in there, but the query isn't printing in the log, as all the rest of the queries do.
This is from my log:
Hibernate: insert into fields (created_by, modified_by, modified_date, category, disabled, hidden, input_type, is_integer, label, max, min, name, is_number, order_by, positive_number, required, suffix, uuid, id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into select_items (descr, field_id, order_by, selected, uuid, id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into select_items (descr, field_id, order_by, selected, uuid, id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into select_items (descr, field_id, order_by, selected, uuid, id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into select_items (descr, field_id, order_by, selected, uuid, id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into select_items (descr, field_id, order_by, selected, uuid, id) values (?, ?, ?, ?, ?, ?)
Hibernate: select field0_.id as id1_18_, field0_.created_by as created_2_18_, field0_.created_date as created_3_18_, field0_.modified_by as modified4_18_, field0_.modified_date as modified5_18_, field0_.category as category6_18_, field0_.disabled as disabled7_18_, field0_.hidden as hidden8_18_, field0_.input_type as input_ty9_18_, field0_.is_integer as is_inte10_18_, field0_.label as label11_18_, field0_.max as max12_18_, field0_.min as min13_18_, field0_.name as name14_18_, field0_.is_number as is_numb15_18_, field0_.order_by as order_b16_18_, field0_.positive_number as positiv17_18_, field0_.required as require18_18_, field0_.suffix as suffix19_18_, field0_.uuid as uuid20_18_ from fields field0_ where field0_.category=? and field0_.name=?
There is no subsequent select statement in the log that would pull the nested SelectItem instances--yet they are there when I get the object back.
So somehow they are being selected, but it doesn't appear that hibernate is doing it, and whatever is selecting them is ignoring the #OrderBy annotation.
Can someone please explain what's going on?
It is missing to specific order type ASC or DESC and call it directly by field name.
#OrderBy("orderBy ASC")
I know there are many questions regarding this issue but I still haven't found a solution for my problem.
I build a PreparedStatement in and pass variables but the error (Unknown column 'checkedAt' in 'field list') is persistent.
My code:
PreparedStatement stmt = conn.prepareStatement(
"IF NOT EXISTS (SELECT * FROM `suites` WHERE name = ?)
THEN INSERT INTO `suites` (`name`, `description`, `metaData`, `active`, `checkedAt`, `createdAt`) VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);
ELSE UPDATE `suites` SET `name` = ?, `description` = ?, `metaData` = ?, `active`= ?, `checkedAt` = CURRENT_TIMESTAMP WHERE `name`= ?; END IF;");
stmt.setString(1, suite.get("SuiteName"));
...
stmt.setInt(9, 1);
stmt.setString(10, suite.get("SuiteName"));
stmt.execute();
The column checkedAt is available in the database and filled. The issue appears only in the UPDATE part (ELSE clause) of the statement.
Does anyone can provide me a solution?
Thank you!
When I try with Spring to udpdate the user with different values, but, for example, without modifying nickname:
//TODO: encripta contraseña monitorDao
public void updateMonitor(Monitor monitor){
BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
String contrasenya = passwordEncryptor.encryptPassword(monitor.getContrasenya());
this.jdbcTemplate.update(
"update Usuario set nickname=?, nombre= ?, apellidos= ?, email= ?, contrasenya = ?, especialidades = ?, telefono = ?",
monitor.getNickname(), monitor.getNombre(), monitor.getApellidos(), monitor.getEmail(),
contrasenya, monitor.getEspecialidades(), monitor.getTelefono()
);
}
This happens:
Request processing failed; nested exception is
org.springframework.dao.DuplicateKeyException:
PreparedStatementCallback; SQL [update Usuario set nickname=?, nombre=
?, apellidos= ?, email= ?, contrasenya = ?, especialidades = ?,
telefono = ?]; ERROR: duplicate key value violates unique constraint
"pk_usuario"
I've never used JDBC templates but it looks like you don't have a where clause in your SQL so you're updating all rows in the database to have those values. You need to restrict it to a single user by adding a where clause:
this.jdbcTemplate.update(
"update Usuario set nickname=?, nombre= ?, apellidos= ?, email= ?, contrasenya = ?, especialidades = ?, telefono = ? where nickname=?",
monitor.getNickname(), monitor.getNombre(), monitor.getApellidos(), monitor.getEmail(),
contrasenya, monitor.getEspecialidades(), monitor.getTelefono(), monitor.getNickname()
);
See http://docs.spring.io/spring/docs/current/spring-framework-reference/html/jdbc.html#jdbc-JdbcTemplate-examples-update
In my opinion you should try this:
this.jdbcTemplate.update(
"update Usuario set nombre= ?, apellidos= ?, email= ?, contrasenya = ?, especialidades = ?, telefono = ? where nickname=?",
monitor.getNombre(), monitor.getApellidos(), monitor.getEmail(),
contrasenya, monitor.getEspecialidades(), monitor.getTelefono(), monitor.getNickname()
);
This won't update the nickname.
I am sorry that i ask a very stupid question but i cant find the place where i miss the comma in the code..
sqlStr.append("INSERT INTO DS_GOAL ");
sqlStr.append("(DS_SITE_CODE, DS_FINANCIAL_YEAR, DS_DEPARTMENT_CODE, DS_PLAN_ID, DS_GOAL_ID, ");
sqlStr.append("DS_DESC, TO_CHAR(DS_PLAN_END_DATE, \"dd/MM/YY\"),");
sqlStr.append("DS_CORP_OBJECTIVE, DS_CORP_OBJECTIVE_OTHER, DS_FOCUS, DS_FOCUS_OTHER, ");
sqlStr.append("DS_TOTAL, DS_EQUIPMENT, DS_RECRUIT, DS_FTE, ");
sqlStr.append("DS_CREATED_USER, DS_MODIFIED_USER, DS_GOAL_ORDER ) ");
sqlStr.append("VALUES ");
sqlStr.append("(?, ?, ?, ?, ?,");
sqlStr.append("?, ?,");
sqlStr.append("?, ?, ?, ?,");
sqlStr.append("?, ?, ?, ?,");
sqlStr.append("?, ?, ?)");
sqlStr_insertGoal = sqlStr.toString();
After the
sqlStr.toString()
the console shows
INSERT INTO DS_GOAL (DS_SITE_CODE, DS_FINANCIAL_YEAR, DS_DEPARTMENT_CODE, DS_PLAN_ID,
DS_GOAL_ID,
DS_DESC, TO_CHAR(DS_PLAN_END_DATE, 'dd/MM/YYYY'),
DS_CORP_OBJECTIVE, DS_CORP_OBJECTIVE_OTHER, DS_FOCUS, DS_FOCUS_OTHER,
DS_TOTAL, DS_EQUIPMENT, DS_RECRUIT,
DS_FTE, DS_CREATED_USER, DS_MODIFIED_USER, DS_GOAL_ORDER)
VALUES (?, ?, ?, ?, ?,?, ?,?, ?, ?, ?,?, ?, ?, ?,?, ?, ?)
After Edited the code
the console shows
INSERT INTO DS_GOAL (DS_SITE_CODE, DS_FINANCIAL_YEAR, DS_DEPARTMENT_CODE, DS_PLAN_ID,
DS_GOAL_ID,
DS_DESC, DS_PLAN_END_DATE,
DS_CORP_OBJECTIVE, DS_CORP_OBJECTIVE_OTHER, DS_FOCUS, DS_FOCUS_OTHER,
DS_TOTAL, DS_EQUIPMENT, DS_RECRUIT,
DS_FTE, DS_CREATED_USER, DS_MODIFIED_USER, DS_GOAL_ORDER)
VALUES (?, ?, ?, ?, ?,?, TO_CHAR(DS_PLAN_END_DATE, 'dd/MM/YYYY'),?, ?, ?, ?,?, ?, ?,
?,?, ?, ?)
But the consoles shows invalid column index error
Thanks for help
I suspect your problem isn't actually a case of a missing comma (in my experience ORA errors are notorious for telling you the wrong thing). My suspicion is that your real issue is the use of " around the format string in your TO_CHAR call. To demonstrate, try this:
SELECT TO_CHAR(SYSDATE, "dd/MM/YY")
FROM DUAL;
If I run the above I get an ORA-00904: "dd/MM/YY": invalid identifier error. If I change the quotes to apostrophes instead:
SELECT TO_CHAR(SYSDATE, 'dd/MM/YY')
FROM DUAL;
I get 16/04/14. Double quotes are for identifiers, not strings:
SELECT TO_CHAR(SYSDATE, 'dd/MM/YY') AS "The Date"
FROM DUAL; // ^ This is an identifier
prints:
The Date
--------
16/04/14
EDIT:
Sorry, I should have spotted this one sooner! You're using TO_CHAR in your columns list, which you can't do. The below example nicely produces an ORA-00917: missing comma error:
CREATE TABLE JON_TEST (COL1 VARCHAR2(20));
COMMIT;
INSERT INTO JON_TEST (TO_CHAR(COL1, 'DD/MM/YYYY'))
VALUES (SYSDATE);
Whereas this works:
INSERT INTO JON_TEST (COL1)
VALUES (TO_CHAR(SYSDATE, 'dd/MM/YYYY'));
So you need to correct three things:
You need to change TO_CHAR to TO_DATE, and
You need to move the call to TO_DATE to your VALUES clause, and
You need to ensure that you use ' instead of " with the format string.
This is how Oracle define the syntax for INSERT statements:
Notice that in the middle section that it only says column_name and not sql_expression.
Try changing your query to the following:
sqlStr.append("INSERT INTO DS_GOAL ")
.append("(DS_SITE_CODE, DS_FINANCIAL_YEAR, DS_DEPARTMENT_CODE, DS_PLAN_ID, DS_GOAL_ID, ")
.append("DS_DESC, DS_PLAN_END_DATE, ")
.append("DS_CORP_OBJECTIVE, DS_CORP_OBJECTIVE_OTHER, DS_FOCUS, DS_FOCUS_OTHER, ")
.append("DS_TOTAL, DS_EQUIPMENT, DS_RECRUIT, DS_FTE, ")
.append("DS_CREATED_USER, DS_MODIFIED_USER, DS_GOAL_ORDER ) ")
.append("VALUES ")
.append("(?, ?, ?, ?, ?,")
.append("?, TO_DATE(?, 'dd/MM/YY'),")
.append("?, ?, ?, ?,")
.append("?, ?, ?, ?,")
.append("?, ?, ?)");
sqlStr_insertGoal = sqlStr.toString();
PreparedStatement update = con.prepareStatement(
"UPDATE employee SET FirstName = ?, LastName = ?, HighestDegreeEarned = ?, JoiningDate = ?, CurrentPost = ?, DeparmentID = ?, ContactNo(Mobile) = ?, ContactNo(Home) = ?, CurrentAddress = ?, PermanentAddress = ? WHERE ID = ?");
update.setString(1, firstnametxt.getText());
update.setString(2, lastnametxt.getText());
update.setString(3, degreetxt.getText());
update.setString(4, joiningdatetxt.getText());
update.setString(5, currentposttxt.getText());
update.setString(6, departmentidtxt.getText());
update.setString(7, mobiletxt.getText());
update.setString(8, contactnotxt.getText());
update.setString(9, currentaddresstxt.getText());
update.setString(10, permanentaddresstxt.getText());
update.setString(11, empidtxt.getText());
update.executeUpdate();
here is the code and on exexuting i m getting the error below.
SQL Exception: java.sql.SQLException: [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near ')'.kindly help me
Column in database can't be named: ContactNo(Mobile) or ContactNo(Home)
If ContactNo() is a function, use dynamic sql to call out it.
There could be two reasons for failing
ContactNo function in SQL server does not exit or not compiled
JoiningDate format is incorrect