How can I get a lazy field in hibernate

How can I get Lazy fields using Entity Manager? Here is my code snippet

public class Internet implements Serializable{ int id; // related fields @ManyToOne (fetch=FetchType.LAZY) Browsers brow; //related public getters and setters. } 

This is my browser hibernate class;

 public class Browser implements Serializable{ int id; String name; //and some other useful fields. //here public getters and setters. public String getName(){ return name; } public void setName(String name){ this.name = name } //and few more. } 

Now my requirement is that I want the name of the browser when I get the browser instance using the EntityManger find method using Internet.id.

These two classes are in different packages. therefore, I cannot directly access browser.name. I need a browser name. when I debug my browser.name program gets zero. Is there any way to get the value of the name browser.name using EntityManager.

I read a few posts related to this question, but I had no idea. Can any body help me?

This is my code, how I use my pages and a few things:

 InternateObjectUsingPage usingPage = (InternateObjectUsingPage)pageWithName(InternateObjectUsingPage.class.getName()); _em = EntityManager.createEntityManager(); Internet ipReg = _em.find(Internet.class, _currentRow.getIpRegId()) ; // _currentRow.getInRegId() is id. ipReg.getBrowser(); // recently i added as per the suggestion. if(ipReg != null){ _refresh = true; usingPage.setInternet(ipReg); return usingPage; } _em.close(); 

that I use my code, but I do not see any difference.

+4
source share
2 answers

You can try this, in a method where you request an Internet object; call internet.getBrowser() to load it at this point.

 Internet internet = (Internet) query.getSingleResult(); // or the way you fetch via EM internet.getBrowser(); 

or if you request a list of objects:

 List<Internet> internetList = (List<Internet>) query.getSingleResult(); // or the way you fetch via EM for(Internet internet: internetList){ internet.getBrowser(); } 

I assume that you specified FetchType.EAGER , since you do not want to download Browser every time you download Internet .

0
source

Assuming you have an EntityManager instance that you are working with in the em variable, and the identifier of the Internet object that will be used in id, I assume that at some point on your first page you call the following:

 Internet internet = em.find(Internet.class, id); 

In the next line of code in the same method, do the following:

 internet.getBrowser(); 

You do not need to do anything with the result, you just need to call the method in the same transaction context as the .find call. Running the property causes EntityManager to load this field. You can then pass your Internet object, and expect the eyebrow property to be non-zero.

0
source

Source: https://habr.com/ru/post/1435535/


All Articles