简体   繁体   English

列出数据库中按给定字段休眠顺序的实体

[英]List entities from database ordered by given field hibernate

I'm starting to learn Hibernate and I'm trying to list entities from postgresql database. 我开始学习Hibernate,并尝试从postgresql数据库中列出实体。 I have a table "dbuser". 我有一个表“ dbuser”。 Then I have a mapping of Dbuser class. 然后我有一个Dbuser类的映射。

@Entity
@Table(name = "dbuser", schema = "public", catalog = "postgres")
public class DbuserEntity {
private int id;
private String username;
private String createdBy;
private Date createdDate;
private String firstName;
private String lastName;

@OrderBy("firstName")
public List<DbuserEntity> dbusers = new ArrayList<DbuserEntity>();

//constructors

@Id
@SequenceGenerator(name="pk_sequence",sequenceName="entity_id_seq", allocationSize=1)
@GeneratedValue(strategy=GenerationType.AUTO,generator="pk_sequence")
@Column(name = "id")
public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

@Basic
@Column(name = "username")
public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

// other getters and setters, equals etc.

Then I have method in class Service to read all entities from table: 然后我在Service类中有方法从表中读取所有实体:

    public List readAll() {
    HibernateUtils hibernateUtils = new HibernateUtils();
    Session session = null;
    List users = new ArrayList<DbuserEntity>();
    try {
        session = hibernateUtils.getSessionFactory().openSession();
        session.beginTransaction();
        users = session.createQuery("FROM DbuserEntity ").list();

        session.beginTransaction().commit();
    } catch (HibernateException e) {
        session.beginTransaction().rollback();
        e.printStackTrace();
    } finally {
        if (session != null) {
            if (session.isOpen()) {
                session.close();
            }
        }
    }
    return users;
}

In main() method I list all entities from table. 在main()方法中,我列出了表中的所有实体。 I want it to be sorted by firstName. 我希望它按名字排序。

      public static void main(String[] args) {   
      Service service = new Service();
      DbuserEntity db = new DbuserEntity();
      List users = new ArrayList<DbuserEntity>();
      users = service.readAll();
      db.dbusers = users;
      for (DbuserEntity dbuser : db.dbusers) {
        System.out.println(dbuser.toString());
    }

 }
 }

And this prints me all dbusers from table. 这会将我桌上的所有dbuser打印出来。

  DbuserEntity{id=19, username='user2', createdby='admin', createddate=2014-11-19, firstname='john', lastname='johnson'}

  DbuserEntity{id=20, username='user3', createdby='admin', createddate=2014-11-19, firstname='ivan', lastname='ivanov'}

  DbuserEntity{id=26, username='newUSer', createdby='system', createddate=2014-11-21, firstname='AAA', lastname='BBB'}

but they are not sorted. 但它们没有排序。 I dont understand what am I doing wrong. 我不明白我在做什么错。 What should I change in my code to print entities sorted? 我应该在代码中进行哪些更改以打印已排序的实体?

createQuery("FROM DbuserEntity order by firstName").list();

生活可以轻松;-)

Try this 尝试这个

public List readAll() {
    HibernateUtils hibernateUtils = new HibernateUtils();
    Session session = null;
    List users = new ArrayList<DbuserEntity>();
    try {
        session = hibernateUtils.getSessionFactory().openSession();
        session.beginTransaction();
        users = session.createQuery("FROM DbuserEntity D ORDER BY D.FirstName ASC").list(); // Here I make changes

        session.beginTransaction().commit();
    } catch (HibernateException e) {
        session.beginTransaction().rollback();
        e.printStackTrace();
    } finally {
        if (session != null) {
            if (session.isOpen()) {
                session.close();
            }
        }
    }
    return users;
}

You can use Criteria to build your queries. 您可以使用条件建立查询。

Criteria criteria = session.createCriteria(DbuserEntity.class).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
criteria.addOrder(Order.asc("firstName"));
List list = criteria.list();

session.beginTransaction().commit();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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