简体   繁体   中英

How to count rows group wise in mysql with java and hibernate?

I have a database "javachat" with one table and two columns. one of these columns is called "nickname" and the second one is "post" so it looks like:

nick1 post1
nick2 post2
nick1 post3
nick2 post4

and now: i need to count how many posts every nickname wrote (i have to count how many nicknames i have in database and how many times they appear). its important that i know the nickname too because i want to create chart with nickname and number of posts.

maybe this question is pretty stupid but i couldnt find anything by searching. the code i wrote for now is just to connect to the database and i have no idea what to do now.

private ???????? downStats() {
        try{
        Session sess = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = sess.beginTransaction();


        tx = null;
        sess.disconnect();

    }
              catch (HibernateException e) {
        if (tx!=null) tx.rollback();
        e.printStackTrace();
        textArea.append("Sorry - could connect to the database!");

    }
    }

any ideas? thank you in advance for any hints.

Assuming your table name is Table

select name, count(post) from Table group by name;


This is how I got your question, and if I got wrongly, then please update your question with expected result.

Please try the following Query

SELECT COLUMN-NAME-OF-NICKNAMES, COUNT(1) FROM TABLENAME GROUP BY COLUMN-NAME-OF-NICKNAMES

This will return each nick name with number of posts.

Here's the associated SQL query you'll have to use:

"SELECT nickname, count(*) FROM my_table GROUP BY nickname"

Now, you need to use Hibernate for this.

sess.createCriteria(MyTable.class)       
    .setProjection(Projections.projectionList()
                   .add(Projections.groupProperty("nickname"))
                   .add(Projections.count("someColumn"))           
    ).list();

Take a look here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM