How to get Eclipselink Entity Manager?

15,430

When you use EclipseLink (via the JPA API) in a Java SE application, you have to set up things a little differently then when your app consists of components running in a Java EE container.

You get an EntityManager with lines like these:

EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-app");
EntityManager em = emf.createEntityManager();

And your application needs to have a persistence.xml file in the META-INF directory of the JAR file of your application. You configure JPA in this file; things you put in there tell Java which persistence provider to use and what the connection parameters for your database are.

The persistence unit name ("my-app" in the example above) must be the same as the name specified in the persistence-unit element in persistence.xml.

See this EclipseLink example, which shows what your persistence.xml has to look like.

EntityManager contains methods such as persist(Object) which you can use to save entities into the database (see these examples that show how to use EntityManager).

Your entity POJO should have a column which will contain the entity id, and it must have a no-args constructor:

@Entity
public class Example {

    @Id
    @GeneratedValue
    private long id;

    // ... Add other properties here

    // Required no-args constructor
    public Example() {
    }

    // ... Add getters and setters here
}

Addition

You can save an entity in the database using the EntityManager like in the following code. No need to use UnitOfWork (as far as I know, UnitOfWork is something you needed when using the older JPA 1.0 API; you don't need this for JPA 2.0):

entityManager.getTransaction().begin();
entityManager.persist(myEntity);
entityManager.getTransaction().commit();
Share:
15,430
MikeZTM
Author by

MikeZTM

Java Apprentice.

Updated on June 04, 2022

Comments

  • MikeZTM
    MikeZTM almost 2 years

    I'm working on a C/S java project and try to use Eclipselink to do the ORM(client side cache database,derby). It's quite easy to do the query with examples & expressions, but when it comes to insert/update, i found that Entity Manager should be used(I'm quite new in java ORM, maybe there's another way?). When i try to create em, it always throw a Exception that telling me i need a server session(i.e. can not find the persistence-unit by name). When i use session bean & @PersistenceUnit annotation, it returns a Null.

    Did I make some stupid mistakes? Or does there any easy way to Update/Insert values? I supposed that there may be some way like session.save(Object) or something like that which can makes this work simple.

    EDIT: I'v tried to use UnitOfWork, but get "Attempt to modify an identity column" error, should i change map file or something that make Eclipselink recognize the identity PK?

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    Add this line in POJO do not work.

    EDIT:I've tried use Unit of work to insert value here's the code

        SessionFactory sessionFactory = new SessionFactory("default");
        Session session = sessionFactory.getSharedSession();
        UnitOfWork uow = session.acquireUnitOfWork();
        SysUser usr2 = new SysUser();
        usr2.setUserName("test");
        usr2.setUserPassword("test");
        uow.registerObject(usr2);
        uow.commit();
    

    But it result in a

    Internal Exception: java.sql.SQLSyntaxErrorException: Attempt to modify an identity column 'DB_ID'.
    

    here's the annotation i used:

    @Column(name = "DB_ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    protected int dbId;
    

    And for EntityManager:

    <persistence-unit name="my-app-name">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>java:/app/jdbc/jdbc/ConnectionDerbyDS</jta-data-source>
    
  • MikeZTM
    MikeZTM over 12 years
    javax.persistence.PersistenceException: No Persistence provider for EntityManager named my-app-name: Provider named org.eclipse.persistence.jpa.PersistenceProvider threw unexpected exception at create EntityManagerFactory: org.eclipse.persistence.exceptions.PersistenceUnitLoadingExc‌​eption
  • Jesper
    Jesper over 12 years
    @MikeZTM do you have all the necessary libraries in your classpath?
  • Jesper
    Jesper over 12 years
    Also, don't use jta-data-source in your persistence.xml in a Java SE application - just specify the JDBC connection parameters (see the example).
  • MikeZTM
    MikeZTM over 12 years
    I've already used javax.persistence.jdbc(this persistence.xml is auto generated by Toplink editor).Classpath seems correct(JDBC driver works well and "org.eclipse.presistence" classes was auto config by JDeveloper)
  • MikeZTM
    MikeZTM over 12 years
    I checked the examples at Eclipsewiki and it suggest to use Unit of Work to do the insert/Update. I tried it and Update works well,but Insert have some problem with the IDENTITY column. should I post a new question for this(or just edit this question)?
  • Jesper
    Jesper over 12 years
    @MikeZTM see my addition above.
  • MikeZTM
    MikeZTM over 12 years
    I find that it seems UnitOfWork still works in JPA2.0. I checked all xml/java and quite confirmed that the name/class/xml were all cerrect but still could not create EntityManager. I even tried to get EM by JNDI lookup and @PresistenceUnit,but it returns null.
  • Jesper
    Jesper over 12 years
    Maybe UnitOfWork still works in JPA 2.0, but why make it more complicated than necessary?
  • MikeZTM
    MikeZTM over 12 years
    THX!! I just found out i missed a line about JTA in my presistence.xml,after delete it. the EM works. thx for ur help :-)