我有两张表如下
@Entity
@Table (name="booking_basic")
public class Booking_Basic {
@Id
@GeneratedValue
@Column (name="booking_id")
private int booking_id;
@GenericGenerator(name="foreign", strategy="foreign", parameters={@org.hibernate.annotations.Parameter(name="property", value="organizer_basic")})
@Column (name="org_id")
private int org_id;
@OneToOne(fetch=FetchType.EAGER, optional=true)
@PrimaryKeyJoinColumn
@Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE})
private Organizer_Basic organizer_basic;
....
另一个是
@Entity
@Table(name="organizer_basic")
public class Organizer_Basic
{
@Id
@GeneratedValue
@Column(name="org_id")
private int org_id;
@Column(name="name")
private String name;
@OneToOne(cascade={javax.persistence.CascadeType.ALL}, fetch=FetchType.LAZY, mappedBy="organizer_basic")
@JoinColumn(name="org_id")
private Booking_Basic booking_basic;
.....
现在我想根据预订ID获取所有组织者名称,如果booking_basic有booking_id 1和org_id = 15,那么我想访问org_id为15的组织者名称。
Session session = HibernateSessionFactory.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Query query = session.createQuery("FROM Booking_Basic");
List<Booking_Basic> booking_basic = query.list();
for(Booking_Basic b : booking_basic)
System.out.print("Booking Type : " + b.getOrganizer_basic().getName());
}
transaction.commit();
}
catch (Exception e) {
e.printStackTrace();
transaction.rollback();
}
但是当我尝试运行它时,它会给我空指针异常。 任何团体都有想法,请帮助我。
答案 0 :(得分:1)
试试这个:
session.createQuery("FROM Booking_Basic as b left join b.organizer_basic as o");