Hi, Is it possible how to get data database tables ,column names and column
values etc ?
I have tried sample snippet code please let me know how to get database column names and values ?
public List<String> getAllTables(){
Map<String, ClassMetadata> classMetaDataMap =
hibernateTemplate.getSessionFactory().getAllClassMetadata();
for(Map.Entry<String, ClassMetadata> metaDataMap : classMetaDataMap.entrySet()) {
ClassMetadata classMetadata = metaDataMap.getValue();
AbstractEntityPersister abstractEntityPersister = (AbstractEntityPersister) classMetadata;
String tableName = abstractEntityPersister.getTableName();
}
}
In hibernate for getting column names use the following:
ClassMetadata classMetadata = sessionFactory.getClassMetadata(Person.class);
String[] propertyNames = classMetadata.getPropertyNames();
And for getting column values you can use Hibernate Criteria.
Criteria criteria = session.createCriteria(Person.class);
List list = criteria.list();
Related
I am not getting output when I am directly passing a list through IN clause, but getting output when passing the values separately.
Working Code below:
List<String> resultList = null;
List<String> list = new ArrayList();
list.add("123");
list.add("456"):
String query = "select * from company where id in('123','456')");
resultList=getJdbcTemplate().queryForList(query, String.class);
Not working code:
List<String> resultList = null;
List<String> list = new ArrayList();
list.add("123");
list.add("456"):
String query = "select * from company where id in(:list)");
resultList=getJdbcTemplate().queryForList(query, String.class);
I want to fetch the query based on the list passed in the query. Could someone help me here
I have created a pojo class Company.java where I have mentioned db column fields.
After the query part,
List<Company> comp = getJdbcTemplate().queryForList(query, Company.class);
Error I am getting :
Incorrect Column count: expected 1, actual 23
What changes I need to do in above line.
I am trying to perform an UPDATE on a MySQL database where I update only one single column full of values corresponding to the correct index position. Here is my current code:
JdbcTemplate temp = new JdbcTemplate(sqlDataSource);
List<Map<String, Object>> results = temp.queryForList("SELECT last_name FROM actor");
List<Object[]> params = new ArrayList<Object[]>();
for (Map<String, Object> row : results) {
params.add(new Object[]{row.get("last_name"), row.get("actor_id")});
}
String sql = "UPDATE actor SET first_name= ? WHERE actor_id=?";
temp.batchUpdate(sql, params)
In this example, I am trying to update all first names in my table to the last names. My main question is how can I include a parameter for the "SET first_name = ?" as well as the WHERE condition "WHERE actor_id = ?" as well? Is this possible with JdbcTemplate?
I think a simple Google search can solve your problem(s).
If you just look up JdbcTemplate batchUpdate, it should guide you in the right direction.
With that said, have a look at these:
https://www.tutorialspoint.com/springjdbc/springjdbc_jdbctemplate
why spring jdbcTemplate batchUpdate insert row by row
I have a method like below
public List<String> getSimilarResourceNames(String resourceName){
String searchString = "%"+resourceName+"%";
Session session = getSession();
Criteria criteria = session.createCriteria(Resource.class);
criteria.add(Restrictions.like("name", searchString));
return criteria.list()
}
This will return me the entire resource from the DB, but what i need is just the name of the resource. How can I accomplish that ?
Use Projection, you can find examples in Hibernate documentation.
Criteria criteria = session.createCriteria(Resource.class);
criteria.setProjection(Property.forName("name"))
criteria.add(Restrictions.like("name", searchString));
By using Projection you will get other fields (Which you did not got by Projection) in your Pojo setted to default values. In HQL you can get specified column values as follow:
Query query = session.createQuery("select u.fullname from Users u");
List<Object[]> rows = query.list();
List<String> fullnames = new ArrayList<String>();
for (Object[] row: rows) {
fullnames.add(row[0]);
}
I hope this will help you.
i need the hql query that should return the Map as result, I tried hql new map query but it returns the list of map like follows
Session session = sessionFactory.getCurrentSession();
String HQL_QUERY = "select new map(user.id as id, user.fullName as fullName)
from User user";
List<Map<String,String>> usersList = session.createQuery(HQL_QUERY).list();
if this is the only solution then how do i convert a list of map into a single map without looping, because if the query returns more rows then the looping take more time for convertion. Help me.
I would suggest using Criteria and then a result transformer to create a map. Have a look at this for official documentation. This gives you a clue and you can find more samples on net.
Creating a map is not the job of HQL. It's your job. Simply loop over the rows you get from the query:
String hql = "select user.id, user.fullName from User user";
List<Object[]> rows = session.createQuery(hql).list();
Map<String, String> result = new HashMap<>();
for (Object[] row : rows) {
result.put((String) row[0], (String) row[1]);
}
you can use map like below
Query query = session.createQuery("select new map(id,username) from UserDetails");
List<?> idUsernameList=query.list();
Iterator<?> iterator = idUsernameList.iterator();
Map row=null;
while(iterator.hasNext()){
row=(Map)iterator.next();
System.out.println(row);
}
I would like to implement the following SQL query with Hibernate Criteria:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name <operator> value
GROUP BY column_name
I have tried to implement this with Hibernate Criteria but it didn't work out.
Can anyone give me an example how this can be done with Hibernate Criteria?
Thanks!
Please refer to this for the example .The main point is to use the groupProperty() , and the related aggregate functions provided by the Projections class.
For example :
SELECT column_name, max(column_name) , min (column_name) , count(column_name)
FROM table_name
WHERE column_name > xxxxx
GROUP BY column_name
Its equivalent criteria object is :
List result = session.createCriteria(SomeTable.class)
.add(Restrictions.ge("someColumn", xxxxx))
.setProjection(Projections.projectionList()
.add(Projections.groupProperty("someColumn"))
.add(Projections.max("someColumn"))
.add(Projections.min("someColumn"))
.add(Projections.count("someColumn"))
).list();
GroupBy using in Hibernate
This is the resulting code
public Map getStateCounts(final Collection ids) {
HibernateSession hibernateSession = new HibernateSession();
Session session = hibernateSession.getSession();
Criteria criteria = session.createCriteria(DownloadRequestEntity.class)
.add(Restrictions.in("id", ids));
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.groupProperty("state"));
projectionList.add(Projections.rowCount());
criteria.setProjection(projectionList);
List results = criteria.list();
Map stateMap = new HashMap();
for (Object[] obj : results) {
DownloadState downloadState = (DownloadState) obj[0];
stateMap.put(downloadState.getDescription().toLowerCase() (Integer) obj[1]);
}
hibernateSession.closeSession();
return stateMap;
}
You can use the approach #Ken Chan mentions, and add a single line of code after that if you want a specific list of Objects, example:
session.createCriteria(SomeTable.class)
.add(Restrictions.ge("someColumn", xxxxx))
.setProjection(Projections.projectionList()
.add(Projections.groupProperty("someColumn"))
.add(Projections.max("someColumn"))
.add(Projections.min("someColumn"))
.add(Projections.count("someColumn"))
).setResultTransformer(Transformers.aliasToBean(SomeClazz.class));
List<SomeClazz> objectList = (List<SomeClazz>) criteria.list();
If you have to do group by using hibernate criteria use projections.groupPropery like the following,
#Autowired
private SessionFactory sessionFactory;
Criteria crit = sessionFactory.getCurrentSession().createCriteria(studentModel.class);
crit.setProjection(Projections.projectionList()
.add(Projections.groupProperty("studentName").as("name"))
List result = crit.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
return result;