I have 3 tables UserDetail, RequestorDetail and AddressDetail. UserDetail is having userId(PK), userName, AddressDetail is having city and suburb, and RequestorDetail is having reqEmail and reqPhone.
I want to update all these details using one query. As of now, I m using 3 different Queries as below.
#Modifying
#Query("update UserDetail u set "u.userName = :userName, u.password = :password where u.userEmailId = :userEmailId")
int saveUserDetailData(#Param("userName") String userName, #Param("password") String password, #Param("userEmailId") String userEmailId);
#Modifying
#Query("update RequestorDetail r set r.requestorEmailid = :requestorEmailid, r.requestorPhone = :requestorPhone where r.userId = :userId")
int saveRequestorDetailData(#Param("requestorEmailid") String requestorEmailid,
#Param("requestorPhone") String requestorPhone, #Param("userId") int userId);
#Modifying
#Query("update AddressDetail a set a.city = :city, a.suburb = :suburb where a.userId = :userId")
int saveAddressDetailData(#Param("city") String city, #Param("suburb") String suburb,
#Param("userId") int userId);
Can anyone please tel me how to use all these in single Query?
It is not possible to update multiple tables with single sql query.
See https://community.oracle.com/thread/2225393
You'll have to split this it into different queries.
Related
In a spring mvc application i have 3 database tables (including one mapping table) and their 2 corresponding java entities.
The entities are:-
public class User {
private Long id;
private String userName;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "user_location",
joinColumns = {#JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {#JoinColumn(name = "location_id", referencedColumnName = "id")}
)
private Set<Location> location;
}
public class Location {
private Long id;
private String locationCode;
}
Three tables are users, location and user_location.
I want to select a user whose location id is equal to a particular id.
Since user can have multiple locations i am not sure how to write a hibernate query for this. I tried few combinations below but i am either getting a exception,
illegal attempt to dereference collection [{synthetic-alias}{non-qualified-property-ref}] with element property reference [id]
or getting a list of User and Location objects. i just want a list of user objects.
from User where userName = :userName and :locationId in (location.id)
from User user inner join user.location loc where user.userName = :usersName and loc.id = :locationId
Update:
I tried query,
Query query = getCurrentSession().createQuery("from User user inner join user.location loc where user.userName = :usersName and loc.id = :locationId");
Hibernate generates following plain SQL from above query and returns a list of User and Location objects. For example if there is one location for an user that matches above query hibernate returns a list that contains one User and one Location object.
select
user0_.id as id1_18_0_,
location2_.id as id1_5_1_,
user0_.user_name as user_na11_18_0_,
location2_.location_code as location3_5_1_
from
users user0_
inner join
user_location location1_
on user0_.id=location1_.user_id
inner join
location location2_
on location1_.location_id=location2_.id
where
user0_.user_name=?
and location2_.id=?
You could try to use next criteria:
Criteria criteria = getCurrentSession().createCriteria(User.class, "u");
criteria.createAlias("location", "loc");
criteria.add(Restrictions.eq("u.userName", "userName");
criteria.add(Restrictions.eq("loc.id", locationId);
List<User> users = criteria.list();
Or you could try HQL typed query:
TypedQuery<User> query =
getCurrentSession().createQuery("SELECT User.* FROM User u JOIN user_location ul ON u.id = ul.user_id JOIN Location l ON ul.location_id = l.id WHERE u.userName = :userName AND l.id = :locationId", User.class)
.setParameter("userName", "userName")
.setParameter("locationOd", locationId);
List<User> users = query.getResultList();
I'm new to HQL and I need help on this error.
QUERY:
String hqlsearchSelect =
"select new com.eteligent.core.loans.paging.LoansAppCustomerPageItem("
+ "main.loanno, (SELECT acct.id.clientid FROM LMSAccountInfo acct WHERE acct.loanno = main.loanno), (SELECT acct.name FROM LMSAccountInfo acct WHERE acct.loanno = main.loanno), main.acctsts, "
+ "main.loanbal, (SELECT acct.matdt FROM LMSAccountInfo acct WHERE acct.loanno = main.loanno) )";
I think the query can't identify which record is it going to return.
CONSTRUCTOR(LoansAppCustomerPageItem):
public LoansAppCustomerPageItem( final String acctNo, final String cifNo, final String customerName, final Integer acctStat, final BigDecimal acctBal, final Date acctDueDate )
{
super();
this.acctNo = acctNo;
this.cifNo = cifNo;
this.customerName = customerName;
this.acctStat = acctStat;
this.acctBal = acctBal;
this.acctDueDate = acctDueDate;
}
If you wanna just one row from subquery use LIMIT 1 at the end of subquery.
so here is my issue:
i have 3 tables:
ROLE : RID ,NAME
CLIENT : CID, NAME
USER : UID, RID, CID, USERNAME, PASSWORD
Below is the SQL statement that I have written:
SELECT USER.UID,USERNAME,PASSWORD,ROLE.NAME, ROLE.RID
FROM USER
INNER JOIN ROLE ON USER.RID=ROLE.RID
WHERE CID=1;
The above statement is returning only 1 row when there should actually be 2 rows.
I don't understand what is not working.
When i do the following, i get my 2 rows:
SELECT *
FROM USER
WHERE CID =1;
Note that i am using spring framework and also implementing a RowMapper. Below is my actual code with the field names as per the dbase.
public List<User> viewUserClient(int client_id) {
String sql =
"SELECT USER.ID,USERNAME,PASSWORD,ACTIVE,ROLE.NAME, ROLE.ID FROM USER INNER JOIN ROLE ON USER.ROLE_ID=ROLE.ID WHERE CLIENT_ID=?";
List<User> users = this.getJdbcTemplate().query(sql, new Object[] { client_id }, new UserClientRowMapper());
return users;
}
private static final class UserClientRowMapper implements RowMapper<User> {
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
Client client = new Client();
Role role = new Role();
user.setID(rs.getInt("ID"));
user.setUSERNAME(rs.getString("USERNAME"));
user.setPASSWORD(rs.getString("PASSWORD"));
user.setACTIVE(rs.getBoolean("ACTIVE"));
role.setNAME(rs.getString("NAME"));
role.setID(rs.getInt("ROLE.ID"));
client.setId(rs.getInt("id"));
client.setName(rs.getString("name"));
user.setRole(role);
user.setClient(client);
return user;
}
}
Thanks in advance for your help.
The INNER JOIN keyword returns rows when there is at least one match in both tables. If there are rows in "USER" that do not have matches in "ROLE", those rows will NOT be listed; of the two users returned by your plain select query, probably one has a null RID column value, or a value that is not in ROLE table.
Use a LEFT JOIN.
I have an error updating my database because of variables. This is my code:
UPDATE `payment` SET `paid`=1 AND `amoun`=$amountpaid WHERE `paid`=0 AND `userid`=$uid
$amountpaid is the amount of the bill that the user paid and $uid is user id. It seems like using $ in front of variable names is forbidden. How can I use variables in SQL?
Where are your variables coming from? You probably want something like this if you're using JDBC:
int setPaid = 1;
int amountPaid = x; // put $amountpaid here
int wherePaid = 0;
int userId = y; // put $uid here
String updateQuery = "UPDATE payment SET paid = ?, amoun = ?"
+ " WHERE paid = ? AND userid = ?";
PreparedStatement ps = con.prepareStatement(updateQuery);
ps.setInt(1, setPaid);
ps.setInt(2, amountPaid);
ps.setInt(3, wherePaid);
ps.setInt(4, userId);
ps.executeUpdate();
I got the solution by using String.
I converted the ArrayList to a String and then sent the data as string. The data got updated but I don't know what will happen next if I want to view the data in the client tier...
My table has the following columns:
User (UserID, GroupID, userName, userType, ...)
I need to do this:
SELECT GroupID
FROM Users
WHERE userID = #userID AND username = #username and usertype = #usertype.
I have my DataContext ready to go, guidance on my LINQ query would be great!
You should download LinqPad and connect to your data source with it. This will really help you get going with LINQ. I also suggest buying the full version ($19) of LinqPad b/c the intellisense can really help you in the beginning
int UserID = [code to get userID],
Usertype=[code to get usertype];
string Username=[code to get username];
from u in Users
where u.userID = UserID
&& username=Username
&& usertype=Usertype
select u.GrupID;
Roughly...
int ID = 1;
string uname = "whatever";
string utype = "whatever"
User myUser = (from u in Users where u.userID == ID && u.username == uname && u.usertype == utype select u).SingleOrDefault();
But yes, grab linqpad
I am not sure if you wanted just one result or a list. I am assuming only one will be found since you are searching on a userID.
string userID = "Your user ID here";
string userName = "Your username here";
string userType = "Your usertype here";
var groupID = (from user in dataContext.Users
where user.UserID == userID &&
user.UserName == userName &&
user.UserType == userType
select user.GroupID).FirstOrDefault();
If you want a list of all the rows that match you could do a ToList() at the end as well.
I haven't tested the code so it could have some typos and I wasn't sure what your variable names were for from your dbml.
var result = from u in users
where u.UserID == userID
&& u.UserName == userName
select u.GroupID