G
grz01
JPA controller Classes in Netbeans 6.5 ?
Hi,
I made a test with a simple table:
create table employee
( id int(11) primary key,
name varchar(255));
In Netbeans 6.5, I created
a Web Application with Spring Web MVC 2.5 support,
a Persistence unit,
and then used
Persistence => Entity Classes from Database
and
Persistence => JPA Controller from entity Classes
which gave me the classes below.
I just wonder now what is the easiest/smartest way to use these
classes under Spring?
Specifically, I noticed there are no setter-methods for
UserTransaction nor EntityManager/EntityManagerFactory in the
templates, so they stayed null when I tried the code.
Am I just supposed to write setter-methods and assign myself, or are
they somehow supposed to be assigned "automagically" through the
@Resource and @PersistenceUnit
annotations?
Or what is the idea exactly?
Anyone can shed some light, please?
Thanks.
EmployeeJpaController.class:
------------------------------------------
package entity;
import entity.exceptions.NonexistentEntityException;
import entity.exceptions.PreexistingEntityException;
import entity.exceptions.RollbackFailureException;
import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.transaction.UserTransaction;
public class EmployeeJpaController {
@Resource
private UserTransaction utx = null;
@PersistenceUnit(unitName = "test01PU")
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Employee employee) throws
PreexistingEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
em.persist(employee);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred
attempting to roll back the transaction.", re);
}
if (findEmployee(employee.getId()) != null) {
throw new PreexistingEntityException("Employee " +
employee + " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Employee employee) throws
NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
employee = em.merge(employee);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred
attempting to roll back the transaction.", re);
}
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = employee.getId();
if (findEmployee(id) == null) {
throw new NonexistentEntityException("The employee
with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(Integer id) throws NonexistentEntityException,
RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
Employee employee;
try {
employee = em.getReference(Employee.class, id);
employee.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The employee
with id " + id + " no longer exists.", enfe);
}
em.remove(employee);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred
attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public List<Employee> findEmployeeEntities() {
return findEmployeeEntities(true, -1, -1);
}
public List<Employee> findEmployeeEntities(int maxResults, int
firstResult) {
return findEmployeeEntities(false, maxResults, firstResult);
}
private List<Employee> findEmployeeEntities(boolean all, int
maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
Query q = em.createQuery("select object(o) from Employee
as o");
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Employee findEmployee(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(Employee.class, id);
} finally {
em.close();
}
}
public int getEmployeeCount() {
EntityManager em = getEntityManager();
try {
return ((Long) em.createQuery("select count(o) from
Employee as o").getSingleResult()).intValue();
} finally {
em.close();
}
}
}
------------------------------------------
Employee.class:
------------------------------------------
package entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
@Entity
@Table(name = "employee")
@NamedQueries({@NamedQuery(name = "Employee.findAll", query = "SELECT
e FROM Employee e"), @NamedQuery(name = "Employee.findById", query =
"SELECT e FROM Employee e WHERE e.id = :id"), @NamedQuery(name =
"Employee.findByName", query = "SELECT e FROM Employee e WHERE e.name
= :name")})
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Column(name = "name")
private String name;
public Employee() {
}
public Employee(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 Employee)) {
return false;
}
Employee other = (Employee) object;
if ((this.id == null && other.id != null) || (this.id != null
&& !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entity.Employee[id=" + id + "]";
}
}
Hi,
I made a test with a simple table:
create table employee
( id int(11) primary key,
name varchar(255));
In Netbeans 6.5, I created
a Web Application with Spring Web MVC 2.5 support,
a Persistence unit,
and then used
Persistence => Entity Classes from Database
and
Persistence => JPA Controller from entity Classes
which gave me the classes below.
I just wonder now what is the easiest/smartest way to use these
classes under Spring?
Specifically, I noticed there are no setter-methods for
UserTransaction nor EntityManager/EntityManagerFactory in the
templates, so they stayed null when I tried the code.
Am I just supposed to write setter-methods and assign myself, or are
they somehow supposed to be assigned "automagically" through the
@Resource and @PersistenceUnit
annotations?
Or what is the idea exactly?
Anyone can shed some light, please?
Thanks.
EmployeeJpaController.class:
------------------------------------------
package entity;
import entity.exceptions.NonexistentEntityException;
import entity.exceptions.PreexistingEntityException;
import entity.exceptions.RollbackFailureException;
import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.transaction.UserTransaction;
public class EmployeeJpaController {
@Resource
private UserTransaction utx = null;
@PersistenceUnit(unitName = "test01PU")
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Employee employee) throws
PreexistingEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
em.persist(employee);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred
attempting to roll back the transaction.", re);
}
if (findEmployee(employee.getId()) != null) {
throw new PreexistingEntityException("Employee " +
employee + " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Employee employee) throws
NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
employee = em.merge(employee);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred
attempting to roll back the transaction.", re);
}
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = employee.getId();
if (findEmployee(id) == null) {
throw new NonexistentEntityException("The employee
with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(Integer id) throws NonexistentEntityException,
RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
Employee employee;
try {
employee = em.getReference(Employee.class, id);
employee.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The employee
with id " + id + " no longer exists.", enfe);
}
em.remove(employee);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred
attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public List<Employee> findEmployeeEntities() {
return findEmployeeEntities(true, -1, -1);
}
public List<Employee> findEmployeeEntities(int maxResults, int
firstResult) {
return findEmployeeEntities(false, maxResults, firstResult);
}
private List<Employee> findEmployeeEntities(boolean all, int
maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
Query q = em.createQuery("select object(o) from Employee
as o");
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Employee findEmployee(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(Employee.class, id);
} finally {
em.close();
}
}
public int getEmployeeCount() {
EntityManager em = getEntityManager();
try {
return ((Long) em.createQuery("select count(o) from
Employee as o").getSingleResult()).intValue();
} finally {
em.close();
}
}
}
------------------------------------------
Employee.class:
------------------------------------------
package entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
@Entity
@Table(name = "employee")
@NamedQueries({@NamedQuery(name = "Employee.findAll", query = "SELECT
e FROM Employee e"), @NamedQuery(name = "Employee.findById", query =
"SELECT e FROM Employee e WHERE e.id = :id"), @NamedQuery(name =
"Employee.findByName", query = "SELECT e FROM Employee e WHERE e.name
= :name")})
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Column(name = "name")
private String name;
public Employee() {
}
public Employee(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 Employee)) {
return false;
}
Employee other = (Employee) object;
if ((this.id == null && other.id != null) || (this.id != null
&& !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entity.Employee[id=" + id + "]";
}
}