I have a small app in which a user uploads a file which carries bunch of id's. I read the file and store all those id's in a list. Now for each id I need to query database so that I could select some other other info. My question is that how to incorporate those id's as part of select statement?
Currently I am querying manually just by typing the id and I want to know how to use getter() as part of query?
Method to select from database
public List<NYProgramTO> getLatestNYData() throws Exception {
String query = "SELECT REQ_XMl, SESSIONID, EXPIRATION_DATE, QUOTE_DATE, POLICY_EFFECTIVE_DATE, TARGET_CREATED, RATING_TRANSACTION_ID, SOURCE_LASTMODIFIED, PREM_WHEN_RERATED FROM dbo.XML_SESSIONS with (nolock) WHERE XML_SESSIONS.LOB = 'PersonalAuto' AND XML_SESSIONS.RATING_STATE = 'NY' AND XML_SESSIONS.ID IN ('72834052') ORDER BY XML_SESSIONS.SOURCE_LASTMODIFIED DESC";
return this.sourceJdbcTemplate.query(query, (rs, rowNum) -> {
NYProgramTO to = new NYProgramTO();
to.setRequestXML(rs.getString("REQ_XML"));
to.setExpirationDate(rs.getDate("EXPIRATION_DATE"));
return to;
});
}
Thanks
You can use MapSqlParameterSource to map the parameter.
public void selectExample(Car car){
String query = "select * from car where id_car = :id and color = :color";
this.sourceJdbcTemplate.query(query, new MapSqlParameterSource("id", car.getId()).addValue("color", car.getColor()), new CarRowMapper());
}
Related
String hql = "select * from myTable where isActive IN (:isActive)";
Query query = session.createQuery(hql);
query.setString("school","");
query.setString("isActive", "Y");//working
query.setString("isActive", "N");//working
query.setString("isActive", "Y","N"); // not working
query.setString("isActive", "'Y','N'"); // not working
return query.list();
I have no idea if the code below should work, I was wondering if i can pass list of values to my search string parameter so there's no need for me to create to queries ; one for select all data regardless of status and another to select only active data.
Use Query.setParameterList() to pass in a List as a parameter:
String hql = "select * from myTable where isActive IN (:isActive)";
Query query = session.createQuery(hql);
List<String> isActiveList = new ArrayList<>();
isActiveList.add("Y");
isActiveList.add("N");
query.setParameterList("isActive", isActiveList);
return query.list();
I need a stored procedure to compare mobile number list in my database table.
Example my table contain 100 rows,I pass java String array to stored procedure to get matching row values return.
The array contain multiple mobile numbers.
If any mobile numbers matched in my table mobile number column value it return row values.
Any possibilities available ?
If available please help me..
I have other solution it's working in spring Jdbc with mysql.
private static final String GET_MATCHING_MOBILE_NUMBERS = "SELECT USER_ID, USER_NAME, REGISTRATION_ID, IMEI_CODE, MOBILE_NUMBER FROM USER WHERE MOBILE_NUMBER IN (";
#Override
#Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public List<UserDO> getMatchingExistingUsers(final String[] mobileNumbers) throws UserDataException {
JdbcTemplate jd = this.getJdbctemplate();
Object[] params = mobileNumbers;
List<UserDO> userDOs = jd.query(getSqlQuery(GET_MATCHING_MOBILE_NUMBERS, mobileNumbers), params, new BeanPropertyRowMapper<UserDO>(UserDO.class));
return userDOs;
}
private String getSqlQuery(String query_string, String[] array_values) {
StringBuilder query_builder = new StringBuilder();
query_builder.append(query_string);
for (#SuppressWarnings("unused")
String values : array_values) {
query_builder.append("?,");
}
query_builder.append("*");
String formated_query = query_builder.toString().replace(",*", ")");
return formated_query;
}
I want Mysql stored procedure if possible for above code..
Advance thanks..
Select query is
private static final String GET_MATCHING_MOBILE_NUMBERS = "SELECT USER_ID, USER_NAME, REGISTRATION_ID, IMEI_CODE, MOBILE_NUMBER FROM USER WHERE FIND_IN_SET(MOBILE_NUMBER,?);";
Jdbc code is
List<UserDO> userDOs = jd.query(GET_MATCHING_MOBILE_NUMBERS, new Object[] { formatedSqlText }, new BeanPropertyRowMapper<UserDO>(UserDO.class));
It's working fine without using String Builder and Stored procedure.
I am a bit lost when it comes to retrieving results from the database.
My MemberModel consists of 4 fields: id, username, password and email. I have been able to successfully save it to database.
Now I need to retrieve an id of a member who's username equals "Test".
I tried something along the lines:
SQLQuery query = session.createSQLQuery("SELECT id FROM members WHERE username = :username");
query.setString("username", username);
List<MemberModel> returnedMembers = query.list();
MemberModel member = returnedMembers.get(0);
int id = member.getId();
However I get an error that member.getId() cannot be converted to int, since it is MemberModel... But the getter getId() returns int.
I am quite confused. The question is: what would be the easiest and fastes way to retrieve member id based on condition (value of username)?
You are using a native SQL query, but should use HQL query. That means you have to change the query to:
session.createQuery("SELECT m FROM MemberModel m WHERE m.username = :username")
I would change your code into something like this:
public MemberModel getMember(String username) {
Query query = sessionFactory.getCurrentSession().createQuery("from " + MemberModel.class.getName() + " where username = :username ");
query.setParameter("username", username);
return (MemberModel) query.uniqueResult();
}
Then you should be able to do:
MemberModel model = someInstance.getMember("someUsername");
int id = model.getId();
You can also use criteria and restrictions api.
Criteria criteria = session.createCriteria(MemberModel.class);
criteria.add(Restrictions.eq("username", username));
MemberModel member=(MemberModel)criteria.uniqueResult();
I want to fetch data from MySQL without creating object from class
Normally I do something like
public ArrayList getInventoryByItemId(String ItemId) throws SQLException {
ArrayList list = new ArrayList<Inventory>();
String sql = "SELECT iid, i.uid, item_data, item_id, i.ctime, username, gender FROM Inventory i JOIN user u ON i.uid = u.uid WHERE item_id = '"+ItemId+"'";
Statement stmt = con.createStatement();
ResultSet rset = stmt.executeQuery(sql);
while (rset.next()) {
a = new Inventory(rset.getInt(1), rset.getInt(2), rset.getString(3), rset.getString(4), rset.getTimestamp(6), rset.getString(7), rset.getString(8));
list.add(a);
}
return list;
}
the problem is because Inventory object does not have user data from the joined user table, I cannot create new Inventory.
I just want to automatically make an object where it has all the data attributes, that I can access using the column name.
Thank You
If I got you problem,
You can create new map(HashMap I reccomend) and put values using column name or index as key.
So, your list will be list of maps.
while (rset.next()) {
a = new HashMap<Integer,Object>();
a.put(1,rset.getInt(1));
..........
list.add(a);
}
Or, If you know exact number of columns, you can user array instead of Map (it will be faster)
Based on what you are saying, I take it that your query is not returning data because the inventory does not have the user data that it is being joined with. You need to modify your query to use a left outer join.
String sql = "SELECT iid, i.uid, item_data, item_id, i.ctime, username, gender FROM Inventory i LEFT JOIN user u ON i.uid = u.uid WHERE item_id = '"+ItemId+"'"
This will allow your query to return Inventory data even if the corresponding User data does not exist.
How can I write DAO method which will return as a result only first entry from the database. For instance lets say I'm looking at Users table and I want to retrieve only the first entry, I'd declare method like:
public User getFirstUser(){
//method logic
}
EDIT:
User has primary key id if that matters at all.
I apologize if this question is too simple/stupid/whatever I'm beginner with Java so I'm trying new things. thank you
My attempt :
public User getFirstUser(){
try {
final String getQuery = "SELECT * FROM Users WHERE Id = (SELECT MIN(Id) FROM Users)";
final Query query = getSession().createQuery(getQuery);
final int rowCount = query.executeUpdate(); // check that the rowCount is 1
log.debug("get successful");
// return what??
} catch (RuntimeException re) {
log.error("get not successful", re);
throw re;
}
}
You can
use:
Query query = session.createQuery("from User");
query.setMaxResults(1);
User result = (User) query.uniqueResult();
use User user = session.get(User.class, id); if you know the ID upfront.
Get all users ordered by id and limit the results to 1 (but don't use LIMIT, use setMaxResults() to remain portable):
Query q = session.createQuery("from User u order by u.id");
q.setMaxResults(1);
User u = (User) q.uniqueResult();
SELECT * FROM Users WHERE Id = (SELECT MIN(Id) FROM Users)
:)
Don't remember exactly but i think there is a method getSingleResult in JPA and also in Hibernate so...
But this method perhaps throw exception when multiple results are returned... can't remember...
Actually there is also getResultList returning a List of entities, and you could do list.get(0) no?
Or create a query with LIMIT 1?
In MS SQL Server we do it like,
First user, min ID,
SELECT TOP 1 * FROM Users ORDER BY Id
Latest user, max ID,
SELECT TOP 1 * FROM Users ORDER BY Id DESC
thanks.