JPA入门实例

建表语句 :
CREATETABLE MyUser (
 id int(11) NOTNULL auto_increment,
 username varchar(200) NOTNULL,
 pwd varchar(20) NOTNULL,
 PRIMARYKEY (id)
) ENGINE=MyISAM DEFAULT CHARSET=GBK;

 jpa的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
    
 <persistence-unit name="JPADemoPU"
  transaction-type="RESOURCE_LOCAL">
  <provider>
   oracle.toplink.essentials.PersistenceProvider
  </provider>
  <class>com.zhaosoft.jpadao.Myuser</class>
  <properties>
   <property name="toplink.jdbc.driver"
    value="com.mysql.jdbc.Driver" />
   <property name="toplink.jdbc.url"
    value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=GBK" />
   <property name="toplink.jdbc.user" value="root" />
  </properties>
 </persistence-unit>

</persistence>

EntityManagerHelper.java

package com.zhaosoft.jpadao;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
/**
 * @author MyEclipse Persistence Tools
 */
public class EntityManagerHelper {
 
 private static final EntityManagerFactory emf; 
 private static final ThreadLocal<EntityManager> threadLocal;
 private static final Logger logger;
 
 static {
  emf = Persistence.createEntityManagerFactory("JPADemoPU");   
  threadLocal = new ThreadLocal<EntityManager>();
  logger = Logger.getLogger("JPADemoPU");
  logger.setLevel(Level.ALL);
 }
  
 public static EntityManager getEntityManager() {
  EntityManager manager = threadLocal.get();  
  if (manager == null || !manager.isOpen()) {
   manager = emf.createEntityManager();
   threadLocal.set(manager);
  }
  return manager;
 }
 
  public static void closeEntityManager() {
        EntityManager em = threadLocal.get();
        threadLocal.set(null);
        if (em != null) em.close();
    }
    
    public static void beginTransaction() {
     getEntityManager().getTransaction().begin();
    }
    
    public static void commit() {
     getEntityManager().getTransaction().commit();
    }  
    
    public static void rollback() {
     getEntityManager().getTransaction().rollback();
    } 
    
    public static Query createQuery(String query) {
  return getEntityManager().createQuery(query);
 }
 
 public static void log(String info, Level level, Throwable ex) {
     logger.log(level, info, ex);
    }
    
}
IMyuserDAO.java

package com.zhaosoft.jpadao;

import java.util.List;

/**
 * Interface for MyuserDAO.
 * 
 * @author MyEclipse Persistence Tools
 */

public interface IMyuserDAO {
 /**
  * Perform an initial save of a previously unsaved Myuser entity. All
  * subsequent persist actions of this entity should use the #update()
  * method. This operation must be performed within the a database
  * transaction context for the entity's data to be permanently saved to the
  * persistence store, i.e., database. This method uses the
  * {@link javax.persistence.EntityManager#persist(Object) EntityManager#persist}
  * operation.
  * 
  * <pre>
  * EntityManagerHelper.beginTransaction();
  * IMyuserDAO.save(entity);
  * EntityManagerHelper.commit();
  * </pre>
  * 
  * @param entity
  *            Myuser entity to persist
  * @throws RuntimeException
  *             when the operation fails
  */
 public void save(Myuser entity);
 /**
  * Delete a persistent Myuser entity. This operation must be performed
  * within the a database transaction context for the entity's data to be
  * permanently deleted from the persistence store, i.e., database. This
  * method uses the
  * {@link javax.persistence.EntityManager#remove(Object) EntityManager#delete}
  * operation.
  * 
  * <pre>
  * EntityManagerHelper.beginTransaction();
  * IMyuserDAO.delete(entity);
  * EntityManagerHelper.commit();
  * entity = null;
  * </pre>
  * 
  * @param entity
  *            Myuser entity to delete
  * @throws RuntimeException
  *             when the operation fails
  */
 public void delete(Myuser entity);
 /**
  * Persist a previously saved Myuser entity and return it or a copy of it to
  * the sender. A copy of the Myuser entity parameter is returned when the
  * JPA persistence mechanism has not previously been tracking the updated
  * entity. This operation must be performed within the a database
  * transaction context for the entity's data to be permanently saved to the
  * persistence store, i.e., database. This method uses the
  * {@link javax.persistence.EntityManager#merge(Object) EntityManager#merge}
  * operation.
  * 
  * <pre>
  * EntityManagerHelper.beginTransaction();
  * entity = IMyuserDAO.update(entity);
  * EntityManagerHelper.commit();
  * </pre>
  * 
  * @param entity
  *            Myuser entity to update
  * @returns Myuser the persisted Myuser entity instance, may not be the same
  * @throws RuntimeException
  *             if the operation fails
  */
 public Myuser update(Myuser entity);
 public Myuser findById(Integer id);
 /**
  * Find all Myuser entities with a specific property value.
  * 
  * @param propertyName
  *            the name of the Myuser property to query
  * @param value
  *            the property value to match
  * @param rowStartIdxAndCount
  *            Optional int varargs. rowStartIdxAndCount[0] specifies the the
  *            row index in the query result-set to begin collecting the
  *            results. rowStartIdxAndCount[1] specifies the the maximum
  *            count of results to return.
  * @return List<Myuser> found by query
  */
 public List<Myuser> findByProperty(String propertyName, Object value,
   int... rowStartIdxAndCount);
 public List<Myuser> findByUsername(Object username,
   int... rowStartIdxAndCount);
 public List<Myuser> findByPwd(Object pwd, int... rowStartIdxAndCount);
 /**
  * Find all Myuser entities.
  * 
  * @param rowStartIdxAndCount
  *            Optional int varargs. rowStartIdxAndCount[0] specifies the the
  *            row index in the query result-set to begin collecting the
  *            results. rowStartIdxAndCount[1] specifies the the maximum
  *            count of results to return.
  * @return List<Myuser> all Myuser entities
  */
 public List<Myuser> findAll(int... rowStartIdxAndCount);
}

Myuser.java

package com.zhaosoft.jpadao;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;

/**
 * Myuser entity.
 * 
 * @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "myuser", catalog = "test", uniqueConstraints = {})
public class Myuser implements java.io.Serializable {

 // Fields

 private Integer id;
 private String username;
 private String pwd;

 // Constructors

 /** default constructor */
 public Myuser() {
 }

 /** full constructor */
 public Myuser(Integer id, String username, String pwd) {
  this.id = id;
  this.username = username;
  this.pwd = pwd;
 }

 // Property accessors
 @Id
 @Column(name = "id", unique = true, nullable = false, insertable = true, updatable = true)
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 public Integer getId() {
  return this.id;
 }

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

 @Column(name = "username", unique = false, nullable = false, insertable = true, updatable = true, length = 200)
 public String getUsername() {
  return this.username;
 }

 public void setUsername(String username) {
  this.username = username;
 }

 @Column(name = "pwd", unique = false, nullable = false, insertable = true, updatable = true, length = 20)
 public String getPwd() {
  return this.pwd;
 }

 public void setPwd(String pwd) {
  this.pwd = pwd;
 }

}

MyuserDAO.java

package com.zhaosoft.jpadao;

import java.util.List;
import java.util.logging.Level;
import javax.persistence.EntityManager;
import javax.persistence.Query;

/**
 * A data access object (DAO) providing persistence and search support for
 * Myuser entities. Transaction control of the save(), update() and delete()
 * operations must be handled externally by senders of these methods or must be
 * manually added to each of these methods for data to be persisted to the JPA
 * datastore.
 * 
 * @see com.zhaosoft.jpadao.Myuser
 * @author MyEclipse Persistence Tools
 */

public class MyuserDAO implements IMyuserDAO {
 // property constants
 public static final String USERNAME = "username";
 public static final String PWD = "pwd";

 private EntityManager getEntityManager() {
  return EntityManagerHelper.getEntityManager();
 }

 /**
  * Perform an initial save of a previously unsaved Myuser entity. All
  * subsequent persist actions of this entity should use the #update()
  * method. This operation must be performed within the a database
  * transaction context for the entity's data to be permanently saved to the
  * persistence store, i.e., database. This method uses the
  * {@link javax.persistence.EntityManager#persist(Object) EntityManager#persist}
  * operation.
  * 
  * <pre>
  * EntityManagerHelper.beginTransaction();
  * MyuserDAO.save(entity);
  * EntityManagerHelper.commit();
  * </pre>
  * 
  * @param entity
  *            Myuser entity to persist
  * @throws RuntimeException
  *             when the operation fails
  */
 public void save(Myuser entity) {
  EntityManagerHelper.log("saving Myuser instance", Level.INFO, null);
  try {
   getEntityManager().persist(entity);
   EntityManagerHelper.log("save successful", Level.INFO, null);
  } catch (RuntimeException re) {
   EntityManagerHelper.log("save failed", Level.SEVERE, re);
   throw re;
  }
 }

 /**
  * Delete a persistent Myuser entity. This operation must be performed
  * within the a database transaction context for the entity's data to be
  * permanently deleted from the persistence store, i.e., database. This
  * method uses the
  * {@link javax.persistence.EntityManager#remove(Object) EntityManager#delete}
  * operation.
  * 
  * <pre>
  * EntityManagerHelper.beginTransaction();
  * MyuserDAO.delete(entity);
  * EntityManagerHelper.commit();
  * entity = null;
  * </pre>
  * 
  * @param entity
  *            Myuser entity to delete
  * @throws RuntimeException
  *             when the operation fails
  */
 public void delete(Myuser entity) {
  EntityManagerHelper.log("deleting Myuser instance", Level.INFO, null);
  try {
   entity = getEntityManager().getReference(Myuser.class,
     entity.getId());
   getEntityManager().remove(entity);
   EntityManagerHelper.log("delete successful", Level.INFO, null);
  } catch (RuntimeException re) {
   EntityManagerHelper.log("delete failed", Level.SEVERE, re);
   throw re;
  }
 }

 /**
  * Persist a previously saved Myuser entity and return it or a copy of it to
  * the sender. A copy of the Myuser entity parameter is returned when the
  * JPA persistence mechanism has not previously been tracking the updated
  * entity. This operation must be performed within the a database
  * transaction context for the entity's data to be permanently saved to the
  * persistence store, i.e., database. This method uses the
  * {@link javax.persistence.EntityManager#merge(Object) EntityManager#merge}
  * operation.
  * 
  * <pre>
  * EntityManagerHelper.beginTransaction();
  * entity = MyuserDAO.update(entity);
  * EntityManagerHelper.commit();
  * </pre>
  * 
  * @param entity
  *            Myuser entity to update
  * @returns Myuser the persisted Myuser entity instance, may not be the same
  * @throws RuntimeException
  *             if the operation fails
  */
 public Myuser update(Myuser entity) {
  EntityManagerHelper.log("updating Myuser instance", Level.INFO, null);
  try {
   Myuser result = getEntityManager().merge(entity);
   EntityManagerHelper.log("update successful", Level.INFO, null);
   return result;
  } catch (RuntimeException re) {
   EntityManagerHelper.log("update failed", Level.SEVERE, re);
   throw re;
  }
 }

 public Myuser findById(Integer id) {
  EntityManagerHelper.log("finding Myuser instance with id: " + id,
    Level.INFO, null);
  try {
   Myuser instance = getEntityManager().find(Myuser.class, id);
   return instance;
  } catch (RuntimeException re) {
   EntityManagerHelper.log("find failed", Level.SEVERE, re);
   throw re;
  }
 }

 /**
  * Find all Myuser entities with a specific property value.
  * 
  * @param propertyName
  *            the name of the Myuser property to query
  * @param value
  *            the property value to match
  * @param rowStartIdxAndCount
  *            Optional int varargs. rowStartIdxAndCount[0] specifies the the
  *            row index in the query result-set to begin collecting the
  *            results. rowStartIdxAndCount[1] specifies the the maximum
  *            number of results to return.
  * @return List<Myuser> found by query
  */
 @SuppressWarnings("unchecked")
 public List<Myuser> findByProperty(String propertyName, final Object value,
   final int... rowStartIdxAndCount) {
  EntityManagerHelper.log("finding Myuser instance with property: "
    + propertyName + ", value: " + value, Level.INFO, null);
  try {
   final String queryString = "select model from Myuser model where model."
     + propertyName + "= :propertyValue";
   Query query = getEntityManager().createQuery(queryString);
   query.setParameter("propertyValue", value);
   if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
    int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
    if (rowStartIdx > 0) {
     query.setFirstResult(rowStartIdx);
    }

    if (rowStartIdxAndCount.length > 1) {
     int rowCount = Math.max(0, rowStartIdxAndCount[1]);
     if (rowCount > 0) {
      query.setMaxResults(rowCount);
     }
    }
   }
   return query.getResultList();
  } catch (RuntimeException re) {
   EntityManagerHelper.log("find by property name failed",
     Level.SEVERE, re);
   throw re;
  }
 }
 public List<Myuser> findByUsername(Object username,
   int... rowStartIdxAndCount) {
  return findByProperty(USERNAME, username, rowStartIdxAndCount);
 }

 public List<Myuser> findByPwd(Object pwd, int... rowStartIdxAndCount) {
  return findByProperty(PWD, pwd, rowStartIdxAndCount);
 }

 /**
  * Find all Myuser entities.
  * 
  * @param rowStartIdxAndCount
  *            Optional int varargs. rowStartIdxAndCount[0] specifies the the
  *            row index in the query result-set to begin collecting the
  *            results. rowStartIdxAndCount[1] specifies the the maximum
  *            count of results to return.
  * @return List<Myuser> all Myuser entities
  */
 @SuppressWarnings("unchecked")
 public List<Myuser> findAll(final int... rowStartIdxAndCount) {
  EntityManagerHelper.log("finding all Myuser instances", Level.INFO,
    null);
  try {
   final String queryString = "select model from Myuser model";
   Query query = getEntityManager().createQuery(queryString);
   if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
    int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
    if (rowStartIdx > 0) {
     query.setFirstResult(rowStartIdx);
    }

    if (rowStartIdxAndCount.length > 1) {
     int rowCount = Math.max(0, rowStartIdxAndCount[1]);
     if (rowCount > 0) {
      query.setMaxResults(rowCount);
     }
    }
   }
   return query.getResultList();
  } catch (RuntimeException re) {
   EntityManagerHelper.log("find all failed", Level.SEVERE, re);
   throw re;
  }
 }

}

测试类:JPATest.java

package com.zhaosoft.test;

import java.util.List;

import com.zhaosoft.jpadao.EntityManagerHelper;
import com.zhaosoft.jpadao.Myuser;
import com.zhaosoft.jpadao.MyuserDAO;

public class JPATest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  EntityManagerHelper.beginTransaction();
  MyuserDAO dao = new MyuserDAO();
  Myuser user = new Myuser();
  user.setUsername("zhaosoft");
  user.setPwd("zhaosoft");
  dao.save(user);
  EntityManagerHelper.commit();
  List<Myuser> result = dao.findAll();
  for (Myuser o : result) {
   System.out.println(o.getId());
   System.out.println(o.getUsername());
  }
 }

}

猜你喜欢

转载自nethub2.iteye.com/blog/2174869