Switch to full style
Java persistent API
Post a reply

Find entity by id

Sun May 09, 2010 12:06 pm

To find entity by id you can search for find function included EntityManager. Follow the example below :

Utility class :
Code:

package com
.codemiles.jpa;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 * @author codemiles.
 */
public abstract class JPAService {
    private EntityManager entityManager;

    public Person findPersonById(String Id) {
    EntityManagerFactory factory = Persistence
            
.createEntityManagerFactory("persistenceUnitName");
    entityManager = factory.createEntityManager();
    entityManager.getTransaction().begin();
    Person person = entityManager.find(Person.class, Id);
    entityManager.getTransaction().commit();
    entityManager.close();
    factory.close();
    if (person != null) {
        System.out.println("Person found  for id = " +Id);
    } else {
        System.out.println("No person found for id = "+Id);
    }
    return person;
    }

}

 


Person entity :
Code:

package com
.codemiles.jpa;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@
Entity
@Table(name="PERSON")
public class Person implements java.io.Serializable{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    @Id
    private String Id
;
    private String name;
    private Date birthday;
    private String gender;
    
    
@OneToOne(mappedBy="person") 
    private Bed bed
;
    
    public String getId
() {
        return Id;
    }
    public void setId(String id) {
        Id = id;
    }
    @Column(name="NAME")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Column(name="BIRTHDAT")
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    @Column(name="GENDER")
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public void setBed(Bed bed) {
    this.bed = bed;
    }
    public Bed getBed() {
    return bed;
    }
 
    
}

 




Post a reply
  Related Posts  to : Find entity by id
 cmp entity beans     -  
 Get all objects for an entity     -  
 JPA entity class example     -  
 @Embeddable entity and @AttributeOverrides     -  
 secondary table per entity     -  
 JPA entity with table generator     -  
 @Transient annotation in JPA entity     -  
 @EntityListeners in your entity class     -  
 create a named query within entity class     -  
 find a string     -  

Topic Tags

Java JPA