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

标签 java mysql spring hibernate

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

我创建了两个实体类 User.javaProfession.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;
}

这是我的 Controller

    @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;
}

最佳答案

这是你的用户类:

  @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类中实现这些方法。如果有人可以提出更正建议,欢迎提出。

关于java - 如何从 hibernate 中的实体类的结果中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31847911/

相关文章:

MYSQL查询返回多个用户输入参数的行数

php - mysqli查询错误,不知道哪里出了问题

Spring Cron 表达式排除某一天在设定时间内运行的作业

PHP如何显示两个表中的行

spring - 一段时间不活动后tomcat连接中断

java - 出现错误 "No converter found capable of converting from type java.lang.String to type org.springframework.security.core.GrantedAuthority"

java - 生产代码 + 测试模块信息 = 不可能?

javascript - 在 JavaScript 函数中等待图像?

java - 如何使用 Maven 的程序集插件将 Implementation-Version 值添加到 jar list ?

java - 如何使用 EJB 实体 bean 连接到 mysql 数据库?