Hibernate 5.4利用对象映射关联查询嵌套实体的实现咨询
实体类修正
你的Doctor实体同时标注了@Entity和@Embeddable,二者功能冲突:@Embeddable用于标注可嵌入到其他实体的非独立对象,而@Entity标注独立存在的数据库表映射实体,你需要删除Doctor类上的@Embeddable注解。同时建议给所有实体类的私有属性添加对应的getter、setter方法,否则Hibernate无法正常读写属性值。
关于hibernate.cfg.xml配置文件的问题
你当前使用JPA标准的EntityManager接口,所有配置都已经在persistence.xml中完成,不需要额外补充Hibernate原生的cfg配置文件,只有使用Hibernate原生Session接口的场景才需要配置该文件。
利用Hibernate对象映射的正确实现方式
完全不需要写原生SQL拼接查询,直接使用JPQL即可利用你已经配置好的关联映射关系,同时使用参数绑定避免SQL注入风险,示例代码如下:
EntityManager entityManager = ... entityManager.getTransaction().begin(); // JPQL直接通过关联关系查询目标Doctor对象 String jpql = "SELECT pd.doctor FROM PrimaryDoctor pd WHERE pd.patient.pid = :pid"; TypedQuery<Doctor> query = entityManager.createQuery(jpql, Doctor.class); // 绑定参数避免SQL注入 query.setParameter("pid", pid); Doctor doctor = query.getSingleResult(); // 直接通过对象属性取值,不需要手动解析结果集 String doctorName = doctor.getName(); String doctorPhone = doctor.getPhone(); entityManager.getTransaction().commit();
如果需要同时用到PrimaryDoctor的其他属性,也可以先查PrimaryDoctor再直接取关联属性:
TypedQuery<PrimaryDoctor> pdQuery = entityManager.createQuery( "SELECT pd FROM PrimaryDoctor pd WHERE pd.patient.pid = :pid", PrimaryDoctor.class ); pdQuery.setParameter("pid", pid); PrimaryDoctor primaryDoctor = pdQuery.getSingleResult(); Doctor doctor = primaryDoctor.getDoctor(); Patient patient = primaryDoctor.getPatient();
如果查询结果可能不存在,建议用getResultList()判断返回集合长度后再取值,避免抛出NoResultException。
内容的提问来源于stack exchange,提问作者Tapal Goosal
相关产品推荐
相关产品推荐

