Tuesday, May 28, 2013

JPA Examples

https://glassfish.java.net/javaee5/persistence/persistence-example.html
CUSTOMER
ID
NAME


ORDER_TABLE
ORDER_ID
SHIPPING_ADDRESS
CUSTOMER_ID
@Entity
public class Customer {

    private int id;
    private String name;
    private Collection
<Order> orders;

    @Id
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public 
String getName() {
        return name;
    }

    public void setName(String 
name) {
        this.
name = name;
    }


    @OneToMany(cascade=ALL, mappedBy="customer")
    public Collection<Order> getOrders() {
        return orders;
    }

    public void setOrders(Collection<Order> newValue) {
        this.orders = newValue;
    }

}


@Entity
@Table(name="ORDER_TABLE")

public class Order {

    private int id;
    private String address;
    private Customer customer;

    @Id
    
@Column(name="ORDER_ID")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    
@Column(name="SHIPPING_ADDRESS")
    public String getAddress() {
        return 
address;
    }

    public void set
Address(String address) {
        this.
address = address;
    }


    @ManyToOne()
    @JoinColumn(name="CUSTOMER_ID")

    public Customer getCustomer
() {
        return 
customer;
    }

    public void setCustomer
(Customer customer) {
        this.
customer = customer;
    }

}

Persisting POJO Entities

Now, let's create new instances, set up the relationships and persist all of them together using the CASCADE option that we set on the Customer entity. This code must be executed in a context of an active transaction.

    // Create new customer
    Customer customer0 = new Customer();
    customer0.setId(1);
    customer0.setName("Joe Smith");

    // Persist the customer
    em.persist(customer0);

    // Create 2 orders
    Order order1 = new Order();
    order1.setId(100);
    order1.setAddress("123 Main St. Anytown, USA");

    Order order2 = new Order();
    order2.setId(200);
    order2.setAddress("567 1st St. Random City, USA");

    // Associate orders with the customer.

Note that the association must be set on both sides of the relationship: on the customer side for the orders to be persisted when transaction commits, and on the order side because it is the owning side:

    customer0.getOrders().add(order1);
    order1.setCustomer(customer0);
 
    customer0.getOrders().add(order2);
    order2.setCustomer(customer0);
When this transaction commits, all three entities will be persisted in the database.

Query and Navigation

We'll use a new EntityManager to do the query, but will execute the query without an active transaction:

    // Create new EntityManager
    em = emf.createEntityManager();

    Query q = em.createQuery("select c from Customer c where c.name = :name");
    q.setParameter("name", "Joe Smith");
    
Our query is supposed to return a single customer, so we will use the Query method getSingleResult() to execute the query. This method would throw an exception if there is no or more than one matching customers.

    Customer c = (Customer)q.getSingleResult();


Now let's verify that the orders were also created by navigating from the Customer. 
You can print the orders, but we'll just check the size:
    
      Collection<Order> orders = c.getOrders();
    if (orders == null || orders.size() != 2) {
        throw new RuntimeException("Unexpected number of orders: "
                + ((orders == null)? "null" : "" + orders.size()));
    }

Merge and Removal of Persistent Instances

To remove an instance, it must be managed by this EntityManager. The code below uses a customer 'c' that had been detached from its persistence context. Removal of the Customer also removes related orders because of the CASCADE option set on the corresponding relationship. This code must be executed in a context of an active transaction.

    // Merge the customer to the new persistence context
    Customer c0 = em.merge(c); //step1

Note that merge() is not a void operation. It returns back a managed copy of the argument (and its related objects). Only this copy can be used for EntityManager operations.

    // Delete all records
    em.remove(c0); //step2


The rest of the configuration of the database and the persistence is on the webpage (NetBeans, GlassFish)
done

Part 2
https://schuchert.wikispaces.com/JPA+Tutorial+1+-+Getting+Started
package entity;
 
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
 
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
 
public class PersonTest {
    private EntityManagerFactory emf;
 
    private EntityManager em;
 
    @Before
    public void initEmfAndEm() {
        BasicConfigurator.configure();
        Logger.getLogger("org").setLevel(Level.ERROR);
 
        emf = Persistence.createEntityManagerFactory("examplePersistenceUnit");
        em = emf.createEntityManager();
    }
 
    @After
    public void cleanup() {
        em.close();
    }
 
    @Test
    public void emptyTest() {
    }
}
Person.java
package entity;
 
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
 
@Entity
public class Person {
    @Id
    @GeneratedValue
    private int id;
    private String firstName;
    private char middleInitial;
    private String lastName;
    private String streetAddress1;
    private String streetAddress2;
    private String city;
    private String state;
    private String zip;
 
    public Person() {
    }
 
    public Person(final String fn, final char mi, final String ln,
            final String sa1, final String sa2, final String city,
            final String state, final String zip) {
        setFirstName(fn);
        setMiddleInitial(mi);
        setLastName(ln);
        setStreetAddress1(sa1);
        setStreetAddress2(sa2);
        setCity(city);
        setState(state);
        setZip(zip);
    }
then getters and setters
}

Update persistence.xml

Inserting and Querying

Add an Embedded Entity

When we created Person we directly included address information into them. This is alright, but what if we want to use Address in another class? Let's introduce a new entity, Address, and make it embedded. This means its fields will end up as columns in the table of the entity that contains it.

Add an Entity with a One to Many Relationship

    @OneToMany
    private Collection<Person> employees;

Make a Relationship Bi-Directional

@ManyToOne(optional = true)
    private Company job;
 
    public Company getJob() {
        return job;
    }
 
    public void setJob(Company job) {
        this.job = job;
    }
 
    // ...
@OneToMany(mappedBy = "job")
    private Collection<Person> employees;
   // update this method //Referential Integrity 
    public void hire(final Person p) {
        getEmployees().add(p);
        p.setJob(this);
    }
 
    // update this method
    public void fire(final Person p) {
        getEmployees().remove(p);
        p.setJob(null);
    }
done

No comments:

Post a Comment