EzDevInfo.com

jpa interview questions

Top jpa frequently asked interview questions

Setting default values for columns in JPA

Is it possible to set a default value for columns in JPA, and if, how is it done using annotations?


Source: (StackOverflow)

Difference between FetchType LAZY and EAGER in Java persistence?

I am a newbie to Java persistence and Hibernate.

What is the difference between FetchType.LAZY and FetchType.EAGER in Java persistence?


Source: (StackOverflow)

Advertisements

JPA EntityManager: Why use persist() over merge()?

EntityManager.merge() can insert new objects and update existing ones.

Why would one want to use persist() (which can only create new objects)?


Source: (StackOverflow)

Hibernate vs JPA vs JDO - pros and cons of each? [closed]

I'm familiar with ORM as a concept, and I've even used nHibernate several years ago for a .NET project; however, I haven't kept up with the topic of ORM in Java and haven't had a chance to use any of these tools.

But, now I may have the chance to begin to use some ORM tools for one of our applications, in an attempt to move away from a series of legacy web services.

I'm having a hard time telling the difference betweeen the JPA spec, what you get with the Hibernate library itself, and what JDO has to offer.

So, I understand that this question is a bit open-ended, but I was hoping to get some opinions on:

  • What are the pros and cons of each?
  • Which would you suggest for a new project?
  • Are there certain conditions when it would make sense to use one framework vs the other?

Source: (StackOverflow)

Weaknesses of Hibernate [closed]

I would like to know which are the weak points of Hibernate 3. This is not pretended to be a thread against Hibernate. I think it will be a very useful knowledge for decide if Hibernate is the best option for a project or for estimating its time.

A weakness can be:

  • A bug
  • Where JDBC or PLSQL are better
  • Performance issues
  • ...

Also, can be useful to know some solutions for that problems, better ORM or techniques, or it will be corrected in Hibernate 4.

For example, AFAIK, Hibernate will have a very bad performance updating 10000 rows comparing to JDBC in this query:

update A set state=3 where state=2

Source: (StackOverflow)

JDO vs JPA for Java on Google App Engine

I want to develop my project on Google App Engine with Struts2. For the database I have two options JPA and JDO. Will you guys please suggest me on it? Both are new for me and I need to learn them. So I will be focused on one after your replies.

Thanks.


Source: (StackOverflow)

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

I would like to load all objects that have a textual tag set to any of a small but arbitrary number of values from our database. The logical way to go about this in SQL would be to build an "IN" clause. JPQL allows for IN, but it seems to require me to specify every single parameter to IN directly (as in, "in (:in1, :in2, :in3)").

Is there some way to specify an array, or a list (or some other container) that should be unrolled to the values of an IN clause?


Source: (StackOverflow)

How to view the SQL queries issued by JPA?

When my code issues a call like this:

entityManager.find(Customer.class, customerID);

How can I see the SQL query for this call? Assuming I don't have access to database server to profile/monitor the calls, is there way to log or view within my IDE the corresponding SQL queries issued by JPA calls? I'm going against SQL Server 2008 R2 using the jTDS driver.


Source: (StackOverflow)

JPA OneToMany not deleting child

I have a problem with a simple @OneToMany mapping between a parent and a child entity. All works well, only that child records are not deleted when I remove them from the collection.

The parent:

@Entity
public class Parent {
    @Id
    @Column(name = "ID")
    private Long id;

    @OneToMany(cascade = {CascadeType.ALL}, mappedBy = "parent")
    private Set<Child> childs = new HashSet<Child>();

 ...
}

The child:

@Entity
public class Child {
    @Id
    @Column(name = "ID")
    private Long id;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="PARENTID", nullable = false)
    private Parent parent;

  ...
}

If I now delete and child from the childs Set, it does not get deleted from the database. I tried nullifying the child.parent reference, but that did not work either.

The entities are used in a web application, the delete happens as part of an Ajax request. I don't have a list of deleted childs when the save button is pressed, so I can't delete them implicitly.


Source: (StackOverflow)

No Persistence provider for EntityManager named

I have my persistence.xml with the same name, using toplink, under META-INF directory. Then I have my code calling it with...

EntityManagerFactory emfdb = Persistence.createEntityManagerFactory("agisdb");

Yet, I got the following error message

2009-07-21 09:22:41,018 [main] ERROR - No Persistence provider for EntityManager named agisdb
javax.persistence.PersistenceException: No Persistence provider for EntityManager named agisdb
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:89)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:60)

Here is the persistence.xml...

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
    <persistence-unit name="agisdb">
        <class>com.agis.livedb.domain.AddressEntity</class>
        <class>com.agis.livedb.domain.TrafficCameraEntity</class>
        <class>com.agis.livedb.domain.TrafficPhotoEntity</class>
        <class>com.agis.livedb.domain.TrafficReportEntity</class>
        <properties>
            <property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/agisdb"/>
            <property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="toplink.jdbc.user" value="root"/>
            <property name="toplink.jdbc.password" value="password"/>
        </properties>
    </persistence-unit>
</persistence>

It should have been in the classpath... Yet, I got the above error... Really appreciate any help... Thanks


Source: (StackOverflow)

How to persist a property of type List in JPA?

What is the smartest way to get an entity with a field of type List persisted?

Command.java

package persistlistofstring;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Persistence;

@Entity
public class Command implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Long id;
    @Basic
    List<String> arguments = new ArrayList<String>();

    public static void main(String[] args) {
        Command command = new Command();

        EntityManager em = Persistence
                .createEntityManagerFactory("pu")
                .createEntityManager();
        em.getTransaction().begin();
        em.persist(command);
        em.getTransaction().commit();
        em.close();

        System.out.println("Persisted with id=" + command.id);
    }
}

This code produces:

> Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named pu: Provider named oracle.toplink.essentials.PersistenceProvider threw unexpected exception at create EntityManagerFactory: 
> oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
> Local Exception Stack: 
> Exception [TOPLINK-30005] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
> Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: sun.misc.Launcher$AppClassLoader@11b86e7
> Internal Exception: javax.persistence.PersistenceException: Exception [TOPLINK-28018] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.EntityManagerSetupException
> Exception Description: predeploy for PersistenceUnit [pu] failed.
> Internal Exception: Exception [TOPLINK-7155] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.ValidationException
> Exception Description: The type [interface java.util.List] for the attribute [arguments] on the entity class [class persistlistofstring.Command] is not a valid type for a serialized mapping. The attribute type must implement the Serializable interface.
>         at oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:143)
>         at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.createEntityManagerFactory(EntityManagerFactoryProvider.java:169)
>         at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:110)
>         at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83)
>         at persistlistofstring.Command.main(Command.java:30)
> Caused by: 
> ...

Source: (StackOverflow)

JPA CascadeType.ALL does not delete orphans

I am having trouble deleting orphan nodes using JPA with the following mapping

@OneToMany (cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "owner")
private List<Bikes> bikes;

I am having the issue of the orphaned roles hanging around the database.

I can use the annotation org.hibernate.annotations.Cascade Hibernate specific tag but obviously I don't want to tie my solution into a Hibernate implementation.

EDIT: It seems JPA 2.0 will include support for this.


Source: (StackOverflow)

JPA fastest way to ignore a field during persistence?

I'm essentially looking for a "@Ignore" type annotation with which I can stop a particular field from being persisted. How can this be achieved?


Source: (StackOverflow)

What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA

what is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA, when see the examples in the web. I see them there used kind of interchangeably. What is the difference between them? Why would you want to use one over the other?


Source: (StackOverflow)

In a bidirectional JPA OneToMany/ManyToOne association, what is meant by "the inverse side of the association"?

In these examples on TopLink JPA Annotation Reference:

Example 1-59 @OneToMany - Customer Class With Generics

@Entity
public class Customer implements Serializable {
    ...
    @OneToMany(cascade=ALL, mappedBy="customer")
    public Set<Order> getOrders() { 
        return orders; 
    }
    ...
}

Example 1-60 @ManyToOne - Order Class With Generics

@Entity
public class Order implements Serializable {
    ...
    @ManyToOne
    @JoinColumn(name="CUST_ID", nullable=false)
    public Customer getCustomer() { 
        return customer; 
    }
    ...
}

It seems to me that the Customer entity is the owner of the association. However, in the explanation for the mappedBy attribute in the same document, it is written that:

if the relationship is bidirectional, then set the mappedBy element on the inverse (non-owning) side of the association to the name of the field or property that owns the relationship as Example 1-60 shows.

However, if I am not wrong, it looks like in the example, the mappedBy is actually specified on the owning side of the association, rather than the non-owning side.

So my question is basically:

  1. In a bidirectional (one-to-many/many-to-one) association, which of the entities is the owner? How can we designate the One side as the owner? How can we designate the Many side as the owner?

  2. What is meant by "the inverse side of the association"? How can we designate the One side as the inverse? How can we designate the Many side as the inverse?


Source: (StackOverflow)