使用hibernate获取数据库记录而不使用主键

时间:2014-08-22 05:44:24

标签: java mysql hibernate

对于我创建的表,我想从没有主键的数据库中获取记录。这是它的模型类。

@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

很难记住每个医生的Doctor_Id,逻辑上First_Name或任何东西都不能成为主键。我所经历的所有教程和讲座视频都是使用 session.get 获取记录的,其中session是Session类的对象。在Session类的源代码中,get的所有重载方法都强制将id作为参数... 他们是解决上述问题的方法吗?

1 个答案:

答案 0 :(得分:3)

有多种选择。以下所有示例都搜索lastName包含 Johnson 的医生。

<强>标准

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();

原生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();

如果你想添加搜索功能,比如说 firstName ,那么你可能想看看Hibernate的Disjunction:Creating a hibernate disjunction query programatically