开发者

Java EE: EJB Entity, Web Standalone

开发者 https://www.devze.com 2023-04-08 05:13 出处:网络
Can you please tell me how is best to do? How can I create a new instance of an entity on web application if I have only the interface..

Can you please tell me how is best to do? How can I create a new instance of an entity on web application if I have only the interface..

I have :

  • EJB(3.1) Project
  • Web project

I have an EJB Project like:

User.java

@Entity
public class User {
    //variables.. getters and setters...
}

UserManagerBean.java

@Stateful
public class UserManagerBean implements UserManager {
    //getters and setters...
    //.......
    public void addUser(User user) {
        //implemented here
    }
    //.......
}

UserManager.java

@Local
@Remote
public interface UserManager {
    //methods here
}

In the web application(a standalone web application) I have this:

UserManager.java

public interface UserManager {
    //methods here
}

User.java

public interface User {
    //methods here
}

Now.. in a bean... I am trying to get from the remote context my beans and use them:

//ctx is created with the specific properties to access remote context..
InitialContext ctx = new InitialContext();
userManager = (UserManager)ctx.lookup("java:global/project/projectEJB/UserManagerBean");

User user = userManager.getUserById(1); //working

User new_user = (User)ctx.lookup("java:global/project/projectEJB/User"); //not working
//I know this is not supposed to work.. but how can I do this?

I know you can't get an instance of an entity because it's not an ejb... Do I have to create a normal class of user having everying as on projectEJB? isn't there a better solution? What other solutions are there? I searched for google and it seems like开发者_JS百科 everybody knows how to do this.. only I don't...

Thank you in advance..


To create the User object you just create a regular Java instance with the 'new' operator and then invoke your EJB call.

User myNewUser = new User();
userManager.addUser(myNewUser);

Both the client side (your web application) and the server side (EJB 3.1 project) must know how to serialize and deserialize the User object therefore each side must have access to the User class and the EJB interfaces.

In terms of packaging you could bundle the EJB interface and User entity class all into a single JAR that is used by both the client and server sides.

An alternative deployment would be to bundle the web app and EJB into a single application deployed inside the same JVM.


Entity beans are not supposed to be created directly in web layer — because for making them persistent them you need the EntityManager, which is not guaranteed to be thread safe (and that's important in a servlet context).

What you probably want to do is writing a DAO EJB with a method to create a new user, inject/look it up in the servlet, and call it. Google for "GenericDAO" pattern to start with.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号