Nadeem Ahmed
Nadeem Ahmed

Reputation: 371

How to fetch data from the result of an entity class in hibernate

I am using hibernate and getting data from two tables.

I create two Entity classes User.java and Profession.java to fetch data from the tables user_table and user_profession.

user_table contains user information and user_profession contains the profession of user with uid as a foreign key. I am getting one record from user_table and getting the profession of that user from user_profession

Here is 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;
}

}

I used @OneToMany annotation here to connect with Profession.java because i want to get the profession of user . Now i got the profession of user but now i want those records from profession table whichs contains same profession as i fetched before.

Here is my 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;
}


}

Here is my Dao class

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

Here is my 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;
}

Upvotes: 1

Views: 3244

Answers (1)

We are Borg
We are Borg

Reputation: 5311

Here is your User class :

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

here is profession class

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

Now comes you DAO class :

 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();
}

For DAO class, please use interface, and your DAOImpl class should implement these methods in DAOImpl class. If anyone can suggest corrections, those are welcome.

Upvotes: 1

Related Questions