Table of Contents
A Simple Sample
persistence.xml – Our starting point
jdbc/pythia false NONE
- Eclipselink is used as our JPA provider
- “javax.persistence.schema-generation.database.action” value=”create” creates database objects if not already there
- “eclipselink.logging.level” value=”FINE” defines the Logging Level – use FINER and FINEST are the next higher levels
- “jdbc/pythia” is our JTA datasource
Create an Entity Object
package de.thnuernberg.in.stuv.pythia.app.model; import javax.persistence.*; import javax.validation.constraints.NotNull; /** * Represents a human user of the system. */ @NamedQueries({ @NamedQuery( name = "Account2.findByLoginName", query = "SELECT user FROM Account2 user WHERE user.loginName LIKE :loginName" ) }) @Entity @Table(name = "Account2") public class Account2 { /** * Primary key. */ @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "accountSequence2") @TableGenerator(name = "accountSequence2") private Long id; @NotNull private String loginName; private String password; /** * Make sure empty constructor exist for persistence framework. */ public Account2() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
Entity Manager related Objects
Account2Dao.java package de.thnuernberg.in.stuv.pythia.app.model.dao; import de.thnuernberg.in.stuv.pythia.app.model.Account2; import javax.ejb.Stateless; import javax.persistence.NoResultException; /** * Entity access object for Account entities. */ @Stateless public class Account2Dao extends AbstractDao{ /** * Find an given Account by its login name. * @param loginName String with login name. * @return Account for login, null if not found. */ public Account2 findAccountByLoginName(String loginName) { assert loginName != null; try { return entityManager.createNamedQuery("Account2.findByLoginName", Account2.class) .setParameter("loginName", loginName) .getSingleResult(); } catch (NoResultException ex) { // if this exception occurs there was no user with given login name. return null; } } } AbstractDao.java package de.thnuernberg.in.stuv.pythia.app.model.dao; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * Providing basic CRUD methods common for all entities. * * @param Type of used Entity. */ public abstract class AbstractDao { @PersistenceContext protected EntityManager entityManager; public void create(T entity) { entityManager.persist(entity); } }