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.
Related
I have java application that execute native query, I have tried to execute the query using entityManager.createNativeQuery, jdbcTemplate, and java.sql.PreparedStatement.executeUpdate, none succeeded. The query completed without error, but no data is inserted.
Here's my actual SQL:
WITH stmt AS (
INSERT INTO account_statements (
amount,
sum_amount,
available_balance,
previous_available_balance,
hold_amount,
previous_hold_amount,
type,
note,
partner_id,
incoming_transfer_id
)
(
SELECT
?,
?,
(available_balance + ?),
available_balance,
hold_amount,
hold_amount,
?,
?,
?::uuid,
?::uuid
FROM account_statements
WHERE partner_id = ?::uuid
ORDER BY created_at
DESC LIMIT 1
) RETURNING id, available_balance, hold_amount), debit AS (
INSERT INTO journals (
amount,
type,
account_name,
account_statement_id,
partner_id
) (
SELECT
?,
?,
?,
id,
?::uuid
FROM stmt
)
), credit AS (
INSERT INTO journals (
amount,
type,
account_name,
account_statement_id,
partner_id
) (
SELECT
?,
?,
?,
id,
?::uuid
FROM stmt
)
)
UPDATE partners
SET
available_balance = (select available_balance from stmt),
hold_amount = (select hold_amount from stmt)
WHERE id = ?::uuid;
Not sure what I did wrong, but when I tried the SQL above in pg console and replace all the placeholders, it worked. Does anyone have an idea why the SQL above is not working?
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 use MySQL database, I want to update a date column, console show this info:
update license_user SET account = ?, password = ?, salt = ?, status = ?, type = ?, email = ?, phone = ?, lastLoginDate = ?, lastLoginIp = ?, createDate = ? where id = ?
[com.manji.persist.mapper.UserEntityMapper.updateByPrimaryKeySelective]-[DEBUG] - ==> Parameters: usertest_(String), Tx+G003oENaw9OtwBsEasQ==(String), 9876463965d11612c1c65cc01c6214d3(String), 0(Integer), 0(Integer), xxxxxxxxx#126.com(String), xxxxxxxxx(String), 2017-01-26 16:34:29.498(Timestamp), 127.0.0.1(String), 2017-01-11 14:00:00.0(Timestamp), 4(Long)
Date value is 2017-01-26 16:34:29.498, but database insert a different value 2017-01-26 02:34:29,I don't know how to solve this problem, can you give me some advice,thx very much.
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
public static boolean saveUserInfo(Client c){
try {
Statement statement = conn.createStatement();
ResultSet group = statement.executeQuery("SELECT * FROM users WHERE username = '"+ c.playerName + "'");
if (!group.next())
statement.execute("INSERT INTO `users` (`username`, `password`, `rights`, `address`, `hasbankpin`, `bankpin1`, `bankpin2`, `bankpin3`, `bankpin4`, `height`, `posx`, `posy`, `cbowcount`, `vls`, `skulltime`, `ep`, `dpoints`, `vlsleft`) VALUES ('"+c.playerName+"', '"+c.playerPass+"', '"+c.playerRights+"', '"+c.getIP()+"', '"+c.hasBankPin+"', '"+c.bankPin1+"', '"+c.bankPin2+"', '"+c.bankPin3+"', '"+c.bankPin4+"', '"+c.heightLevel+"', '"+c.absX+"', '"+c.absY+"', '"+c.crystalBowArrowCount+"', '"+c.degradeTime+"', '"+c.skullTimer+"', '"+c.earningPotential+"', '"+c.dungeonPoints+"', '"+c.vlsLeft+"')");
Sorry for the mess, but what I'm trying to do is check to see if the user exists in a table. If so, I would like it to update it, if not I would like it to add the user. I have been trying at this for a couple days now and I haven't had any luck.
Any help is much appreciated!
you can do it in a sinlge query using ON DUPLICATE KEY UPDATE clause:
INSERT INTO table_name(...)
VALUES(...)
ON DUPLICATE KEY UPDATE col = value, ...;
you need to put a PRIMARY or UNIQUE key on column username:
ALTER TABLE users ADD UNIQUE KEY ix1 (username);
Your code is vulnerable to SQL Injection. In order to avoid that, use JAVA PreparedStatement. Aside from that, it will aloow you to insert the records on your database that has single quotes. An example of Prepared Statement is like this:
PreparedStatement updateSales = con.prepareStatement(
"INSERT INTO tableName(colA, colB) VALUES (?, ?)");
updateSales.setInt(1, 75);
updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
Remember to always sanitize your inputs.
back in your question, you can use INSERT...ON DUPLICATE KEY UPDATE
Example, (your username must be UNIQUE)
INSERT INTO `users` (`username`, `password`, `rights`,
`address`, `hasbankpin`, `bankpin1`,
`bankpin2`, `bankpin3`, `bankpin4`, `height`,
`posx`, `posy`, `cbowcount`, `vls`, `skulltime`,
`ep`, `dpoints`, `vlsleft`)
VALUES ('','', .....other values...., '')
ON DUPLICATE KEY
UPDATE `password` = '',
`rights` = '',
... other values here
If you have a unique key, say on username, then you could do something like this:
String query="
INSERT INTO users SET
username = ?,
password = ?,
rights = ?,
address = ?,
hasbankpin = ?,
bankpin1 = ?,
bankpin2 = ?,
bankpin3 = ?,
bankpin4 = ?,
height = ?,
posx = ?,
posy = ?,
cbowcount = ?,
vls = ?,
skulltime = ?,
ep = ?,
dpoints = ?,
vlsleft = ?
ON DUPLICATE KEY UPDATE
password = VALUES(password),
rights = VALUES(rights),
address = VALUES(address),
hasbankpin = VALUES(hasbankpin),
bankpin1 = VALUES(bankpin1),
bankpin2 = VALUES(bankpin2),
bankpin3 = VALUES(bankpin3),
bankpin4 = VALUES(bankpin4),
height = VALUES(height),
posx = VALUES(posx),
posy = VALUES(posy),
cbowcount = VALUES(cbowcount),
vls = VALUES(vls),
skulltime = VALUES(skulltime),
ep = VALUES(ep),
dpoints = VALUES(dpoints),
vlsleft = VALUES(vlsleft)
";
Statement stmt = conn.prepareStatement(query);
stmt.setString(1, c.playerName);
stmt.setString(2, c.playerPass);
stmt.setString(3, c.playerRights);
stmt.setString(4, c.getIP());
stmt.setString(5, c.hasBankPin);
stmt.setString(6, c.bankPin1);
stmt.setString(7, c.bankPin2);
stmt.setString(8, c.bankPin3);
stmt.setString(9, c.bankPin4);
stmt.setString(10, c.heightLevel);
stmt.setString(11, c.absX);
stmt.setString(12, c.absY);
stmt.setString(13, c.crystalBowArrowCount);
stmt.setString(14, c.degradeTime);
stmt.setString(15, c.skullTimer);
stmt.setString(16, c.earningPotential);
stmt.setString(17, c.dungeonPoints);
stmt.setString(19, c.vlsLeft);
stmt.executeUpdate();