[英]Fetch database records using hibernate without using Primary Key
I want to fetch records from database without the primary key, for a table that i have created. 对于我创建的表,我想从没有主键的数据库中获取记录。 Here is the model class for it.
这是它的模型类。
@Entity
@Table(name = "DOCTORS_INFORMATION")
public class DoctorInformation {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "DOCTOR_ID")
private int ID;
@Column(name = "FIRST_NAME")
private String firstName;
@Column(name = "LAST_NAME")
private String lastName;
@Column(name = "ADDRESS_LINE1")
private String addressLine1;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "CITY")
private Location location;
//along with setters and getters
It is very difficult to remember the Doctor_Id for every doctor, and logically First_Name or anything cannot be made a primary key. 很难记住每个医生的Doctor_Id,逻辑上First_Name或任何东西都不能成为主键。 All the tutorials and lecture videos that i have gone through fetch records using session.get where session is an object of class Session.
我所经历的所有教程和讲座视频都使用session.get获取记录,其中session是Session类的对象。 In the source code of Session class all the overloaded methods of
get
mandatory take id as a parameter... Is their a workaround for the above problem? 在Session类的源代码中,
get
强制的所有重载方法都将id作为参数...它们是针对上述问题的解决方法吗?
There are multiple options. 有多种选择。 All of the following examples search for a doctor whose lastName contains Johnson .
以下所有示例都搜索lastName包含Johnson的医生。
Criteria 标准
String lastNameToSearchFor = "Johnson";
List doctors = session.createCriteria(DoctorInformation.class)
.add( Restrictions.like("lastName", "%"+lastNameToSearchFor+"%") ) // the leading wild card can become a problem since it cannot be indexed by the DB!
.addOrder( Order.asc("lastName") )
.list();
HQL HQL
String lastNameToSearchFor = "Johnson";
String hql = "FROM " + DoctorInformation.class.getName() + " di WHERE di.lastName LIKE :lastName ORDER BY di.lastName ASC";
Query query = session.createQuery(hql);
query.setParameter("lastName", "%" + lastNameToSearchFor + "%"); // again, the leading wild card may be a problem
List doctors = query.list();
Native SQL 原生SQL
String lastNameToSearchFor = "Johnson";
String sql = "SELECT * FROM DOCTORS_INFORMATION WHERE lastName LIKE :lastName ORDER BY lastName ASC";
Query query = session.createSQLQuery(sql).addEntity(DoctorInformation.class);
query.setString("lastName", "%" + lastNameToSearchFor + "%"); // again, the leading wild card may be a problem
List doctors = query.list();
If you want to add capability to search with, let's say firstName , then you might want to look into Hibernate's Disjunction: Creating a hibernate disjunction query programatically 如果你想添加搜索功能,比如firstName ,那么你可能想看看Hibernate的Disjunction: 以编程方式创建一个hibernate disjunction查询
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.