Hot questions for Using Enterprise JavaBeans in netbeans

Question:

i use JPA eclipse Toplink & EJB

everytime i receive entity from database then change some data inside of it,

database(MYSQL) automaticly change too without i commit or do something

Example:

Player p = em.findById(1);
p.setName(newName);
// i do nothing , but database automaticly change

i already read related question here, but i still can't figure it out

i think i must detach entity but i don't know how to do this, because

i have class GenericDAO generated from netbeans

GenericDAO (generated from netbeans)

public abstract class GenericDAO<T> {
    private Class<T> entityClass;

    public GenericDAO(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    protected abstract EntityManager getEntityManager();

    public void insert(T entity) {
        getEntityManager().persist(entity);
    }

    public void edit(T entity) {
        getEntityManager().merge(entity);
    }

    public void delete(T entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }

    public T findById(Object id) {
        return getEntityManager().find(entityClass, id);
    }

    public List<T> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return getEntityManager().createQuery(cq).getResultList();
    }

    public List<T> findRange(int[] range) {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        q.setMaxResults(range[1] - range[0] + 1);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public int count() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
        cq.select(getEntityManager().getCriteriaBuilder().count(rt));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }

}

DaoPlayer

@Local
public interface DaoPlayer{
    void insert(Player player);

    void edit(Player player);

    void delete(Player player);

    Player findById(Object id);

    List<Player> findAll();

    List<Player> findRange(int[] range);

    int count();

ImplPlayer

@Stateless
public class ImplPlayer extends GenericDAO<Player> implements DaoPlayer{
    @PersistenceContext(unitName = "MonsterPuzzle")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public ImplPlayer() {
        super(Player.class);
    }

}

My question is

  • how to disable JPA automaticly save to database?
  • ( Because i think i need to detach )how to detach the entity from GenericDAO?

Answer:

Understand this: "every update in an attached entity will be reflected in the database".

When an entity is attached? To put it in a simple way, every entity that pass through the EntityManager with the methods: persist, merge, refresh, delete (maybe I am forgetting some any other here) or in the query (JPQL or find) methods inside a transaction.

Look at the sample below:

entityManager.getTransaction().begin();
Dog dog = entityManager.find(Dog.class, 1);
dog.setGoodBoyLevel(99);
entityManager.getTransaction().commit();

Since dog passed by the find method inside a transaction it can be considered managed.

If you are using EJB you must know that the default transaction is REQUIRED. The REQUIRED works like: If there is a transaction opened, let us use it. If there is no transaction opened, let us open it. (It is a nice guy)

Since your method is without any indicator to suspend the transaction every update in the entity will be reflected in the database. What could you do? Use the NOT_SUPPORTED transaction way:

@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void yourMethod(){
    // to awesome things
}

Since you are using the NOT_SUPPORTED transaction option your entity will be detached. What does detached means? The JPA will not analyse the updates in the entity. If you want just read some info, that is ok. But the code below will raise exception:

entityManager.getTransaction().begin();
Dog dog = new Dog();
Owner owner = getDetachedOwner(ownerId);
dog.setOwner(owner);
entityManager.persist(dog);
entityManager.getTransaction().commit();

The problem here is that the owner is detached, so the JPA do not knows it and would raise an exception.

Be careful with the NOT_SUPPORTED option. [=

Question:

I'm following the JEE7 first cup directions for EJB:

Before you can create applications based on the archetypes, you must first install the archetypes and supporting projects to your local Maven repository.

In NetBeans IDE select File, then Open Project, navigate to tut-install/, 
select example, deselect the Open Required Projects check box, and click
Open Project.

Right-click the firstcup project in the Projects pane and select Build.

Only I don't see tut-install, and this seems to be the only reference to tut-install...

While I have, I think, installed maven, I don't see dukes-age:

Create the Project in NetBeans IDE 
    From the File menu, select New Project.
    Under Categories, select Maven.
    Under Projects, select Project from Archetype.
    Click Next.
    In the Search field, enter dukes-age.
    In the Known Archetypes field, select dukes-age-archetype.
    Click Next.
    In the Project Name field, enter dukes-age.
    In the Package field, enter firstcup.dukesage.resource.
    Click Finish.

When browsing archetypes, I see:

why doesn't the dukes-age project show up?


Answer:

Here is what I figured. Throwing it here as additional info.

The archtypes are not available in the glassfish install that comes packaged with Netbeans 8.0.1. I downloaded Java EE SDK update 1 from http://www.oracle.com/technetwork/java/javaee/downloads/index.html.

Once the downloaded .zip is extracted, the java_ee_sdk-7u1\glassfish4\docs\firstcup\example folder contains the archtypes.

Question:

Its Strange i create new EJB Project and when i add any dependency using maven it always throws this exception saying that library not found while i have checked that the location is present and so is the jar present.

java.lang.IllegalArgumentException: Specified library jar commons-io-2.4.jar does not exist: C:\Users\Umer%20Kiani\.m2\repository\commons-io\commons-io\2.4\commons-io-2.4.jar
at org.glassfish.deployment.common.DeploymentContextImpl.getAppLibs(DeploymentContextImpl.java:458)
at org.glassfish.deployment.common.DeploymentContextImpl.createClassLoader(DeploymentContextImpl.java:244)
at org.glassfish.deployment.common.DeploymentContextImpl.createDeploymentClassLoader(DeploymentContextImpl.java:229)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:365)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:360)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:360)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:189)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:745)

here is my POM.xml file

<?xml version="1.0" encoding="UTF-8"?>

http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0

<groupId>com.selflearning</groupId>
<artifactId>TestProject</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>ejb</packaging>

<name>JpaApplication</name>

<properties>
    <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>eclipselink</artifactId>
        <version>2.5.2</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
        <version>2.5.2</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>

    </dependency>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
                <compilerArguments>
                    <endorseddirs>${endorsed.dir}</endorseddirs>
                </compilerArguments>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-ejb-plugin</artifactId>
            <version>2.3</version>
            <configuration>
                <ejbVersion>3.1</ejbVersion>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.6</version>
            <executions>
                <execution>
                    <phase>validate</phase>
                    <goals>
                        <goal>copy</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${endorsed.dir}</outputDirectory>
                        <silent>true</silent>
                        <artifactItems>
                            <artifactItem>
                                <groupId>javax</groupId>
                                <artifactId>javaee-endorsed-api</artifactId>
                                <version>7.0</version>
                                <type>jar</type>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>


Answer:

The main problem is that you are packaging as EJB, which results in a JAR file. JAR files can't contain dependencies (because these are other JAR files).

One quick solution, which I wouldn't recommend, is to place the dependencies in the lib folder of your Glassfish installation, this makes the dependencies available to all applications deployed on the server.

The better solution is to package your application as WAR (results in a WAR file) or EAR (results in an EAR file). Have a look at my answer on this question for details how to do that.

Question:

(Sorry for my english, that not my first language, but I will try to be the more clear possible).

I have to make an application based on Java EJB that can communicate with other projects through RMI for some services. But I also want to make some other services - that allow to proceed business functions on my entities - available through an REST interface. And there is where I am lost.

I created several projects on Netbeans :

  • exampleApp which is composed of modules :

    • exampleApp-ejb
    • exampleApp-ear
    • exampleApp-web
  • exampleAppShared (for my RMI service)

For the moment, my services look like :

@Stateless
public class ServicesClient implements ServicesClientLocal {

@EJB
private GestionClientLocal gestionClient;

//code refering to business functions
}

My RMI part functions well. But I don't know how to make my services available through an REST services. Should I create another project ?

Maybe I did search badly but I didn't find some answers here or on internet about this case...

Thanks in advance for who will take some time to answer to my (idiot) question...


Answer:

Finally I found !

I just need to create with netbeans the REST webservice :

  • right click on the package you want to create your webservice
  • new
  • RestFul webservices from patterns

Just click the first screen and then choose the name of the webservice. Then you can do a call of an enterprise bean.

Question:

Hi I'm new to EJB (NetBeans), I'm trying to retrieve Named queryProperty.findAll via my servlet but I'm having a problem. this the problem

non static method cannot be referenced from a static context where T is a type of variable

AbstractFacade class

public abstract class AbstractFacade<T> {

    private Class<T> entityClass;

    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    protected abstract EntityManager getEntityManager();

    public void create(T entity) {
        getEntityManager().persist(entity);
    }

    public void edit(T entity) {
        getEntityManager().merge(entity);
    }

    public void remove(T entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }

    public T find(Object id) {
        return getEntityManager().find(entityClass, id);
    }

    public List<T> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return getEntityManager().createQuery(cq).getResultList();
    }

    public List<T> findRange(int[] range) {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        q.setMaxResults(range[1] - range[0] + 1);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public int count() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
        cq.select(getEntityManager().getCriteriaBuilder().count(rt));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }

}

Entity class (Property)

@Entity
@Table(name = "property")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Property.findAll", query = "SELECT p FROM Property p")
    , @NamedQuery(name = "Property.findByPropertyId", query = "SELECT p FROM Property p WHERE p.propertyId = :propertyId")
    , @NamedQuery(name = "Property.findByPropertyType", query = "SELECT p FROM Property p WHERE p.propertyType = :propertyType")
    , @NamedQuery(name = "Property.findByNumOfBedroom", query = "SELECT p FROM Property p WHERE p.numOfBedroom = :numOfBedroom")
    , @NamedQuery(name = "Property.findByNumOfBathroom", query = "SELECT p FROM Property p WHERE p.numOfBathroom = :numOfBathroom")
    , @NamedQuery(name = "Property.findByAddress", query = "SELECT p FROM Property p WHERE p.address = :address")
    , @NamedQuery(name = "Property.findByDescription", query = "SELECT p FROM Property p WHERE p.description = :description")
    , @NamedQuery(name = "Property.findByFurnish", query = "SELECT p FROM Property p WHERE p.furnish = :furnish")
    , @NamedQuery(name = "Property.findByGarden", query = "SELECT p FROM Property p WHERE p.garden = :garden")
    , @NamedQuery(name = "Property.findByArea", query = "SELECT p FROM Property p WHERE p.area = :area")
    , @NamedQuery(name = "Property.findByBuyType", query = "SELECT p FROM Property p WHERE p.buyType = :buyType")
    , @NamedQuery(name = "Property.findByPropertyPrice", query = "SELECT p FROM Property p WHERE p.propertyPrice = :propertyPrice")})
public class Property implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "PropertyId")
    private Integer propertyId;
    @Size(max = 45)
    @Column(name = "PropertyType")
    private String propertyType;
    @Column(name = "NumOfBedroom")
    private Long numOfBedroom;
    @Column(name = "NumOfBathroom")
    private Long numOfBathroom;
    @Size(max = 250)
    @Column(name = "Address")
    private String address;
    @Size(max = 500)
    @Column(name = "Description")
    private String description;
    @Size(max = 45)
    @Column(name = "Furnish")
    private String furnish;
    @Size(max = 45)
    @Column(name = "Garden")
    private String garden;
    @Column(name = "Area")
    private Long area;
    @Size(max = 45)
    @Column(name = "BuyType")
    private String buyType;
    @Column(name = "PropertyPrice")
    private Integer propertyPrice;
    @Lob
    @Column(name = "ImageUrl")
    private byte[] imageUrl;
    @OneToMany(mappedBy = "propertyId")
    private Collection<Offer> offerCollection;
    @JoinColumn(name = "agentsId", referencedColumnName = "AgentsId")
    @ManyToOne
    private Agents agentsId;
    @JoinColumn(name = "OwnerId", referencedColumnName = "OwnerId")
    @ManyToOne
    private Owner ownerId;

    public Property() {
    }

    public Property(Integer propertyId) {
        this.propertyId = propertyId;
    }

    public Integer getPropertyId() {
        return propertyId;
    }

    public void setPropertyId(Integer propertyId) {
        this.propertyId = propertyId;
    }

    public String getPropertyType() {
        return propertyType;
    }

    public void setPropertyType(String propertyType) {
        this.propertyType = propertyType;
    }

    public Long getNumOfBedroom() {
        return numOfBedroom;
    }

    public void setNumOfBedroom(Long numOfBedroom) {
        this.numOfBedroom = numOfBedroom;
    }

    public Long getNumOfBathroom() {
        return numOfBathroom;
    }

    public void setNumOfBathroom(Long numOfBathroom) {
        this.numOfBathroom = numOfBathroom;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getFurnish() {
        return furnish;
    }

    public void setFurnish(String furnish) {
        this.furnish = furnish;
    }

    public String getGarden() {
        return garden;
    }

    public void setGarden(String garden) {
        this.garden = garden;
    }

    public Long getArea() {
        return area;
    }

    public void setArea(Long area) {
        this.area = area;
    }

    public String getBuyType() {
        return buyType;
    }

    public void setBuyType(String buyType) {
        this.buyType = buyType;
    }

    public Integer getPropertyPrice() {
        return propertyPrice;
    }

    public void setPropertyPrice(Integer propertyPrice) {
        this.propertyPrice = propertyPrice;
    }

    public byte[] getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(byte[] imageUrl) {
        this.imageUrl = imageUrl;
    }

    @XmlTransient
    public Collection<Offer> getOfferCollection() {
        return offerCollection;
    }

    public void setOfferCollection(Collection<Offer> offerCollection) {
        this.offerCollection = offerCollection;
    }

    public Agents getAgentsId() {
        return agentsId;
    }

    public void setAgentsId(Agents agentsId) {
        this.agentsId = agentsId;
    }

    public Owner getOwnerId() {
        return ownerId;
    }

    public void setOwnerId(Owner ownerId) {
        this.ownerId = ownerId;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (propertyId != null ? propertyId.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Property)) {
            return false;
        }
        Property other = (Property) object;
        if ((this.propertyId == null && other.propertyId != null) || (this.propertyId != null && !this.propertyId.equals(other.propertyId))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "Entities.Property[ propertyId=" + propertyId + " ]";
    }

}

Servelt page

@Override
    public void init() throws ServletException {
        List<Property> PropertyList= PropertyFacade.findAll();   
        getServletContext().setAttribute("property", PropertyList);       

    }

PropertyFacade class

public class PropertyFacade extends AbstractFacade<Property> {

    @PersistenceContext(unitName = "testRealPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public PropertyFacade() {
        super(Property.class);
    }

Answer:

Since findAll is not static, you need to create an instance of your PropertyFaƧade. You can't just call PropertyFacade.findAll(). In spring, you would get this instance from the ApplicationContext, not sure how it is being created in ejb.

Note: mind the naming convention in java: the variables start with lowercase letter and the classes start with an uppercase letter. So, you should change PropertyList to propertyList.