my question is how to insert values into DB in sql. i have a USER who can have multiple emails. how can i insert multiple emails into one object? i dont want to add a completely new user object into a new row. i just want to update and append new email into email field of an existing user in db.
i did this:
JPA.em().createQuery
("insert into User (email) select (email) from User where USERNAME=? VALUES (?)")
.setParameter(1, username).setParameter(2, email).executeUpdate();
but it is not working, thanks for help !!
Get the user from the database, concatenate its existing email with the new value, and save the user.
JPA uses entities and generates SQL queries for you. You tyically use queries only to get entities from the database. And those queries are JPQL queries, not SQL queries.
And it looks like your schema is not normalized correctly. One User entity should have many Email entities (OneToMany associations), rather than stuffing all the emails in a single CLOB field of the user. This is how you could search and get individual emails from the database, and get users without all their emails if you don't need them.
I don't know JPA but query should be
JPA.em().createQuery
("insert into User (email) select (email) from User where USERNAME=? VALUES (?)")
.setParameter(1, username).setParameter(2, email).executeUpdate();
should be
JPA.em().createQuery("UPDATE User
SET email =?
WHERE USERNAME=? ")
.setParameter(1,email )
.setParameter(2,username)
.executeUpdate();
Related
I need one help.
I have a table - ACCOUNT which stores USER_ID and ACCOUNT_DETAIL. There are multiple records for a single USER_ID with different ACCOUNT_DETAIL.
I want to store this records in a Map where USER_ID will be the key and List of Account will be the value. I get the list of USER_ID
from USER table. Then for each of those user id I need to get account details.
I can populate that map by implementing below algorithm\logic :
Step 1 : Fetch userIds from USER table and store it in a list - userList
Step 2:
for (User user : userList) {
// Make a DB call to ACCOUNT table for user.id
// Put those details in the map - map.put(user.id, accountList)
}
But here the issue is, if USER table is having 1K records I have to make 1K db calls from that loop which will end up with a performance issue.
Could you please tell me if there is any better approach through which I can achieve this using hibernate ?
Use the HQL join query(ACCOUNT and USER) to get all the accounts and construct the map by iterating the accounts.
select acc from Account acc, User usr where acc.userId = usr.id
I'm testing SQL injection in my lab and need to combine two SQL queries using UNION to bypass authentication, so I would like to know if there is a way to set static values in second query, so that my JAVA code will check will only check for the user password I send as static password : The SQL Query should be like this :
SELECT * FROM users WHERE user = 'user1' UNION SELECT user AS
user1, password AS password FROM users ;'
My JAVA code reports an error :
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to
use near
First, eliminate the use of SELECT * to make sure both queries return the same number of columns. Then you can hard code your static values in the second query.
SELECT user, password
FROM users
WHERE user = 'user1'
UNION
SELECT 'user', 'password';
Using union
You must select the corresponding number type of column eg:
SELECT user, password
FROM users
WHERE user = 'user1'
UNION
SELECT 'user', 'password'
;
How to write A crud Query which can only fetch two colmun from my db?
suppose there are 4 columns in my db - (id,city,pincode,state) and i need only city,picode from crudRepository query
For example, it can be done like this:
SELECT city, pincode
FROM tableName;
If it is about SQL, then will help you:
SELECT table_name.city, table_name.pincode FROM table_name;
It works if there is already a connection to DB.
I have a web application in which a user must log into. I am using Hibernate to save objects to the MySQL database. In the database i have triggers which insert new records into audit tables when ever an insert/update/delete is done on an object
DELIMITER $$
CREATE TRIGGER `trg_insert_Book` BEFORE INSERT ON Book FOR EACH ROW
BEGIN
INSERT INTO audit_book (AUDITTYPE,AUDITDATE,bookId, bookName, pages) VALUES ('I',NOW(), NEW.bookId, NEW.bookName, NEW.pages);
END; $$
DELIMITER ;
As you can see from the trigger above i am inserting a new record into the audit_book table when ever an insert is done on the Book table. The insert is done using the following code
public void addNewBook(Book book) {
Session session = sessionFactory.getCurrentSession();
session.save(book);
}
I have a method which returns the user that is currently using the system
#ModelAttribute("username")
public String getPerson(Principal principal) {
return principal.getName();
}
My question is how can i pass this username to the database so that the username is added to the audit table without adding the username to the Book object?
No, you can't do it that way, because the database is not aware of the logic about identifying application users.
You could consider using Hibernate Envers instead of database triggers for auditing purposes. In the linked example you can see how to accomplish your goal in the section 4. Add username information to each revision.
i want to call two table of different database at once.table of database A contains user id and table of database B contains user location with the user id, so i want to join these two tables and get the location corresponding to user_id.database A and B are in two different servers. so how can i join these two tables. if it is not possible to join this, is there any efficient way to do this.please help.i'm trying to do this using java, mysql.
ps = con.prepareStatement("SELECT user_id FROM A.users");
rs = ps.executeQuery();
while(rs.next())
{
//call select statement for database B to get the location for each user id
}
please suggest an efficient way to do this
Id User_id
===========
1 44
2 23
User_id location
====================
44 india
23 us
Supposing user_id is a long.
PreparedStatement psUserLocation = conB.prepareStatement("SELECT location FROM B.users WHERE user_id = ?");
while(rs.next()) {
//call select statement for database B to get the location for each user id
long userId = rs.getLong(user_id);
psUserLocation.setLong(1, userId)
ResultSet userLocation = ps.executeQuery();
// Do whatever with the location(s)
}
EDIT: one query for all users instead of one query per user:
private final static String QUERY = "SELECT user_id, location FROM B.users WHERE user_id IN (%a)";
StringBuilder userList = new StringBuilder();
while(rs.next()) {
long userId = rs.getLong(user_id);
userList.append(userId);
if (!rs.isLast()) {
userList.append(",");
}
}
String usersLocationQuery = QUERY.replaceAll("%a", userList.toString());
PreparedStatement psUsersLocation = conB.prepareStatement(usersLocationQuery);
ResultSet usersLocation = psUsersLocation.executeQuery();
// Do whatever with the locations
Keep in mind this can fail/work wrong because most DB have a limit for how many items an SQL IN clause can include. Also this second method might allow an SQL injection on the %a replacement.
You may use FEDERATED Storage Engine. The FEDERATED storage engine lets you access data from a remote MySQL database without using replication or cluster technology. Querying a local FEDERATED table automatically pulls the data from the remote (federated) tables. No data is stored on the local tables. This may not be very efficient but it will do the work (JOINs).
If you can do away with join, one possible way is to get all the user_id's from tableA in one go, and then pass the user_id's to tableB at once. Of course, this approach will require you to change code as well.
Something like:
select user_id from tableA (of databaseA);
and
select user_id, location from tableB (of database B) where user_id in (<result_from_above_query)
The above process will require two queries.