我正在使用弹簧休息创建一个休眠的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中这样做。这是我的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;
}
这是我的用户类
@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;
}
请帮助我,我陷入了休眠状态。
答案 0 :(得分:1)
当您使用ORM时,您需要考虑对象及其相互之间的关系,而不是数据库表,列,外键等。虽然您可以将表和列直接映射到类和字段,但是因为将应用程序数据视为对象图并使用ORM管理该图的真正目的将被打败,所以这样做不会有太多的里程。
如果你改变:
@Column(name="author_id")
private long author_id;
public long getAuthor_id() { return author_id; }
public void setAuthor_id(long author_id) { this.author_id = author_id; }
为:
@JoinColumn(name = "author_id")
@ManyToOne(fetch = FetchType.LAZY)
private User author;
public User getAuthor() { return author; }
public void setAuthor(User author) { this.author = author; }
只要您有Alert
个对象,只需在其上调用getAuthor
即可获得可以直接使用的User
对象。
此更改不需要对数据库进行任何更改。