我开始学习Hibernate,并试图从postgresql数据库中列出实体。我有一张桌面“dbuser”。然后我有一个Dbuser类的映射。从给定字段hibernate排序的数据库列表实体
@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.
然后,我有方法,一流的服务,从表中读取所有实体:
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;
}
在main()方法,我列出的所有实体从表。我希望它按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());
}
}
}
而这会打印出表格中的所有dbusers。
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'}
但他们没有排序。我不明白我做错了什么。我应该更改我的代码以打印排序的实体?
作为一个方面说明,如果您没有对语句进行更改,则不需要提交或回滚。 – Kraylog 2014-11-22 15:33:57