简体   繁体   中英

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. All the tutorials and lecture videos that i have gone through fetch records using session.get where session is an object of class 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?

There are multiple options. All of the following examples search for a doctor whose lastName contains 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

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

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

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