| /******************************************************************************* |
| * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved. |
| * This program and the accompanying materials are made available under the |
| * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 |
| * which accompanies this distribution. |
| * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html |
| * and the Eclipse Distribution License is available at |
| * http://www.eclipse.org/org/documents/edl-v10.php. |
| * |
| * Contributors: |
| * Oracle - initial impl |
| ******************************************************************************/ |
| package example; |
| |
| |
| import javax.persistence.EntityManager; |
| import javax.persistence.EntityManagerFactory; |
| import javax.persistence.Persistence; |
| |
| /** |
| * Uses EclipseLink JPA to read/write an object to a database. |
| * @author James Sutherland |
| */ |
| public class DatabaseSerializer implements Serializer { |
| EntityManagerFactory factory; |
| Class lastClass; |
| Object lastId; |
| |
| public DatabaseSerializer() { |
| this.factory = Persistence.createEntityManagerFactory("order"); |
| } |
| |
| public byte[] serialize(Object object) { |
| EntityManager em = this.factory.createEntityManager(); |
| em.getTransaction().begin(); |
| em.persist(object); |
| this.lastClass = object.getClass(); |
| this.lastId = this.factory.getPersistenceUnitUtil().getIdentifier(object); |
| em.getTransaction().commit(); |
| return new byte[]{}; |
| } |
| |
| public Object deserialize(byte[] bytes) { |
| EntityManager em = this.factory.createEntityManager(); |
| return em.find(this.lastClass, this.lastId); |
| } |
| |
| public String toString() { |
| return getClass().getSimpleName(); |
| } |
| } |