import jpadao.*;
import java.util.*;
/**
* JPA 测试运行代码.
* @author BeanSoft
*
*/
public class JPARun {
public static void main(String[] args) {
// 开始事务
EntityManagerHelper.beginTransaction();
// 创建 DAO
MyuserDAO dao = new MyuserDAO();
// 创建实体类
Myuser user = new Myuser();
user.setUsername("jpa test 文 ");
user.setPassword("jpa password");
// 保存
dao.save(user);
// 提交事务真正保存实体到数据库
EntityManagerHelper.commit();
// 列出数据库中所有对象
List<Myuser> result = dao.findAll();
for(Myuser o : result) {
System.out.println(o.getId());
System.out.println(o.getUsername());
}
}
}
EntityManagerHelper 类
/**
* @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 Query createQuery(String query) {
return getEntityManager().createQuery(query);
}
public static void log(String info, Level level, Throwable ex) {
logger.log(level, info, ex);
}
}
MyuserDAO 类实现了ImyuserDAO接口
/**
* Data access object (DAO) for domain model class Myuser.
*
* @see jpadao.Myuser
* @author MyEclipse Persistence Tools
*/
public class MyuserDAO implements IMyuserDAO {
// property constants
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
private EntityManager getEntityManager() {
return EntityManagerHelper.getEntityManager();
}
public void save(Myuser transientInstance) {
EntityManagerHelper.log("saving Myuser instance", Level.INFO, null);
try {
getEntityManager().persist(transientInstance);
EntityManagerHelper.log("save successful", Level.INFO, null);
} catch (RuntimeException re) {
EntityManagerHelper.log("save failed", Level.SEVERE, re);
throw re;
}
}
public void delete(Myuser persistentInstance) {
EntityManagerHelper.log("deleting Myuser instance", Level.INFO, null);
try {
getEntityManager().remove(persistentInstance);
EntityManagerHelper.log("delete successful", Level.INFO, null);
} catch (RuntimeException re) {
EntityManagerHelper.log("delete failed", Level.SEVERE, re);
throw re;
}
}
public Myuser update(Myuser detachedInstance) {
EntityManagerHelper.log("updating Myuser instance", Level.INFO, null);
try {
Myuser result = getEntityManager().merge(detachedInstance);
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;
}
}
@SuppressWarnings("unchecked")
public List<Myuser> findByProperty(String propertyName, Object value) {
EntityManagerHelper.log("finding Myuser instance with property: "
+ propertyName + ", value: " + value, Level.INFO, null);
try {
String queryString = "select model from Myuser model where model."
+ propertyName + "= :propertyValue";
return getEntityManager().createQuery(queryString).setParameter(
"propertyValue", value).getResultList();
} catch (RuntimeException re) {
EntityManagerHelper.log("find by property name failed",
Level.SEVERE, re);
;
throw re;
}
}
public List<Myuser> findByUsername(Object username) {
return findByProperty(USERNAME, username);
}
public List<Myuser> findByPassword(Object password) {
return findByProperty(PASSWORD, password);
}
@SuppressWarnings("unchecked")
public List<Myuser> findAll() {
EntityManagerHelper.log("finding all Myuser instances", Level.INFO,
null);
try {
String queryString = "select model from Myuser model";
return getEntityManager().createQuery(queryString).getResultList();
} catch (RuntimeException re) {
EntityManagerHelper.log("find all failed", Level.SEVERE, re);
;
throw re;
}
}
}
ImyuserDAO接口
package jpadao;
import java.util.List;
/**
* Interface for MyuserDAO.
*
* @author MyEclipse Persistence Tools
*/
public interface IMyuserDAO {
public void save(Myuser transientInstance);
public void delete(Myuser persistentInstance);
public Myuser update(Myuser detachedInstance);
public Myuser findById(Integer id);
public List<Myuser> findByProperty(String propertyName, Object value);
public List<Myuser> findByUsername(Object username);
public List<Myuser> findByPassword(Object password);
public List<Myuser> findAll();
}
Myuser 类
package 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 generated by 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 password;
// Constructors
/** default constructor */
public Myuser() {
}
/** full constructor */
public Myuser(Integer id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
// 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 = "password", unique = false, nullable = false, insertable = true, updatable = true, length = 20)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
}
36 + 102 + 27 + 66 = 231 行代码
作为增删改查的业务逻辑,非常易于理解。
但实现这种业务逻辑,采用Spring MVC + JPA + Hibernate + TOMCAT 7.0 + SQLServer 来实现J2EE应用的常用配置模板就是另外一回事了。