如何从hibernate中的实体类结果中获取数据

时间:2015-08-06 06:03:31

标签: java mysql spring hibernate

我正在使用hibernate并从两个表中获取数据。

我创建了两个实体类 User.java Profession.java 来从表user_table和user_profession中获取数据。

user_table包含用户信息,user_profession包含uid作为外键的用户职业。我从user_table获取一条记录,并从user_profession

获得该用户的职业

这是 User.java

@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="full_name")
private String fullName;

@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name="u_id")
private List<Profession> prof;  


public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

public List<Profession> getProf() {
    return prof;
}

public void setProf(List<Profession> prof) {
    this.prof = prof;
}

public String getFullName() {
    return fullName;
}

public void setFullName(String fullName) {
    this.fullName = fullName;
}

}

我在这里使用 @OneToMany 注释与Profession.java连接,因为我想获得用户的职业 。现在我得到了用户的职业,但现在我希望那些职业表中的记录包含与我之前提取的职业相同的职业。

这是我的Profession.java

@Entity
@Table(name="user_profession")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Profession implements Serializable {


private static final long serialVersionUID = 1L;


@Id
@GeneratedValue
@Column(name="id")
private long id;

@Column(name="u_id")
private long uid;

@Column(name="profession")
private String profession;

@Column(name="type")
private String professionType;

@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name="u_id")
private List<User> prof;  



//Getters and setters

public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

public long getUid() {
    return uid;
}

public void setUid(long uid) {
    this.uid = uid;
}

public String getProfession() {
    return profession;
}

public void setProfession(String profession) {
    this.profession = profession;
}


public String getProfessionType() {
    return professionType;
}

public void setProfessionType(String professionType) {
    this.professionType = professionType;
}


}

这是我的 Dao

@Autowired
SessionFactory sessionFactory;

Session session = null;
Transaction tx = null;

@SuppressWarnings({ "unchecked", "rawtypes" })
public List<User> getUserById(long id) throws Exception {
    session = sessionFactory.openSession();
    Criteria cr = session.createCriteria(User.class);
    cr.add(Restrictions.eq("id", id));
    List results = cr.list();
    tx = session.getTransaction();
    session.beginTransaction();
    tx.commit();
    return results;
}

@SuppressWarnings({ "unchecked", "rawtypes" })
public List<Profession> getProfessionById(long id) throws Exception {
    session = sessionFactory.openSession();
    Criteria cr = session.createCriteria(Profession.class);
    cr.add(Restrictions.eq("u_id", id));
    List results = cr.list();
    tx = session.getTransaction();
    session.beginTransaction();
    tx.commit();
    return results;
}

这是我的控制器

    @Autowired
SubscribeDataService subscribeService;

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public @ResponseBody
List<User> getSubscriber(@PathVariable("id") long id) {

    List<User> user = null;

    try {
        user = subscribeService.getUserById(id);


    } catch (Exception e) {
        e.printStackTrace();
    }

    return user;
}

1 个答案:

答案 0 :(得分:0)

这是您的用户类:

  @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="full_name")
    private String fullName;

    @OneToMany(cascade=CascadeType.REMOVE, fetch=FetchType.LAZY)
    private Set<Profession> prof;  
    // getters and setters
    }

这是专业课

@Entity
@Table(name="user_profession")
// i have no idea why you need such JSONIgnore, but ok
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Profession implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
@Column(name="id")
private long id;

@Column(name="u_id")
private long uid;

@Column(name="profession")
private String profession;

@Column(name="type")
private String professionType;

@ManyToOne
 @JoinColumn(name = "userid", nullable = false)
    private User usersProfession
// getters and metters
}

现在来DAO班:

 private final SessionFactory sessionFactory;

    @Autowired
    public DAOClasname(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

// I am presuming you want user and passing user id.
    // Don't just throw Exception, use something meaningful
public User getUserById(long id){
        Session session = this.sessionFactory.getCurrentSession();
return (User)session.get(User.class,id);

}

// I am presuming you are passing user id and expect users profession
// Don't just throw Exception, use something meaningful
public List<Profession> getProfessionById(long id){
        Session session = this.sessionFactory.getCurrentSession();
   org.hibernate.Query query = session.createQuery("from Profession as P where p.usersProfession.userId=:id");
   query.setParameter("id",id);
return query.list();
}

对于DAO类,请使用interface,DAOImpl类应该在DAOImpl类中实现这些方法。如果有人可以建议更正,欢迎这些。