JPA+Hibernate3 CRUD(增删改查操作)

JPA与Hibernate3结合的CRUD(增删改查操作)

  
    
package com.archie.test;

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

import com.archie.model.User;

/**
* CRUD操作测试
*
@author archie2010
* since 2011-4-19下午22:13:26
*/
public class CrudTest {
public static void addUser(){
EntityManagerFactory factory
= Persistence.createEntityManagerFactory("jpaTest");
// EntityManager相当于Hibernate中session
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
// 保存(持久化)方法
em.persist(new User("Tom"));
em.getTransaction().commit();
em.close();
factory.close();
}
/**
* 删除
*/
public static void deleteUser(){
EntityManagerFactory factory
= Persistence.createEntityManagerFactory("jpaTest");
EntityManager em
= factory.createEntityManager();

em.getTransaction().begin();
User user
= em.find(User.class, 1);
em.remove(user);
em.getTransaction().commit();

em.close();
factory.close();
}
//=======================查询
/**
* find方法相当于Hibernate中的get方法,
* getReference方法相当于Hibernate中的load方法,具有延迟加载的作用;
* 当查找的对象不存在时,find的方法返回null值,
* 而getReference方法则抛出异常javax.persistence.EntityNotFoundException
*/

/**
* 查询byFind
*/
public static void findUserByFind(){

EntityManagerFactory factory
= Persistence.createEntityManagerFactory("jpaTest");
EntityManager em
= factory.createEntityManager();

//Find方法相当于Hibernate中的get方法
User user = em.find(User.class, 1);

System.out.println(user.getUserName());

em.close();
factory.close();
}
/**
* 查询ByReference
*/
public static void findUserByReference(){
EntityManagerFactory factory
= Persistence.createEntityManagerFactory("jpaTest");
EntityManager em
= factory.createEntityManager();

//getReference方法相当于Hibername中的load方法,具有延迟加载的功能
User user = em.getReference(User.class, 1);

System.out.println(user.getUserName());

em.close();
factory.close();
}
/**
* 更新
*/
public static void updateUser(){
EntityManagerFactory factory
= Persistence.createEntityManagerFactory("jpaTest");
EntityManager em
= factory.createEntityManager();

em.getTransaction().begin();
User user
= em.find(User.class, 1);
user.setUserName(
"tom_new");
//相当于hibernate将游离状态下的数据更新到数据库中
em.getTransaction().commit();

em.close();
factory.close();
}
/**
* 更新
* 将游离状态下的数据更新到数据库中
*/
public static void updateUserByMerge(){
EntityManagerFactory factory
= Persistence.createEntityManagerFactory("jpaTest");
EntityManager em
= factory.createEntityManager();

em.getTransaction().begin();
User user
= em.find(User.class, 1);
//把实体管理器中的实体变成游离状态
em.clear();
user.setUserName(
"tom_Merge");
//把游离状态下的更新同步到数据库中
em.merge(user);
em.getTransaction().commit();

em.close();
factory.close();
}
/**
* main方法测试
*
@param args
*/
public static void main(String[] args) {
/*findUserByFind();
findUserByReference();
updateUserByMerge();
deleteUser();
*/
addUser();
}
}

你可能感兴趣的:(hibernate3)