1
我正在使用spring rest在hibernate中創建一個Web應用程序,並且我卡在兩個表格之間。我想要映射一個表列與另一個表列。我已經在jsp中完成了,但現在我想在hibernate中完成。我從alert表中獲取author_id,然後我想從user_table中獲取該作者id的配置文件圖片。如何在休眠狀態下使用另一個表格列來映射表格列
JSP代碼:
<%
String sql = "select author_id from alert where id=2";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
String aid = rs.getString("author_id");
String sql1 = "select profile_img from user_table where id='"+aid+"'";
Statement st1 = con.createStatement();
ResultSet rs1 = st1.executeQuery(sql1);
while(rs1.next()){
String image_name = rs1.getString("profile_img");
}
}
%>
我想這樣做在hibernate.Here是我Alert類
@Entity
@Table(name="alert")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Alert implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name="id")
private long id;
@Column(name="author_id")
private long author_id;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getAuthor_id() {
return author_id;
}
public void setAuthor_id(long author_id) {
this.author_id = author_id;
}
這裏是我的User類
@Entity
@Table(name="user_table")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name="id")
private long id;
@Column(name="profile_img")
private String img_name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getImg_name() {
return img_name;
}
public void setImg_name(String img_name) {
this.img_name = img_name;
}
}
這裏是我的DAO等級:
@Autowired
SessionFactory sessionFactory;
Session session = null;
Transaction tx = null;
public User getUserById(long id) throws Exception {
session = sessionFactory.openSession();
User user = (User) session.load(User.class, new Long(id));
tx = session.getTransaction();
session.beginTransaction();
tx.commit();
return user;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<Alert> getAlertById(long id) throws Exception {
session = sessionFactory.openSession();
Criteria cr = session.createCriteria(Alert.class);
cr.add(Restrictions.eq("alert_viewer_id", id));
List alert = cr.list();
tx = session.getTransaction();
session.beginTransaction();
tx.commit();
return alert;
}
請幫我,我被困在冬眠。
哪裏會創建警報對象? –
在上面的SQL代碼中,您有一個警報ID。您啓動一個SQL查詢以獲取具有該ID的警報的作者ID。然後,您再次啓動第二個SQL查詢,以便使用先前檢索的ID獲取用戶的配置文件映像。使用Hibernate,如果你使用'session.createCriteria(Alert.class).add(Restrictions.eq(「id」,alertId).uniqueResult()',你將得到一個Alert對象,其id等於'alertId'變量,這相當於上面的第一個查詢,然後你只需在'alert'對象上''alert.getAuthor()。getImg_name()'' – manish
兄弟請更改我的代碼併發布我無法理解,因爲我在休眠 –