JPA学习之二(入门篇)

  简单总结下,JPA的入门。在学习JPA的时候运用参考Hibernate的知识来进行学习。

开发环境及其配置:
引用

  Eclipse3.5
  依赖包:
     antlr-2.7.6.jar
    c3p0-0.9.1.jar
    cglib-2.2.jar
    commons-collections-3.1.jar
    dom4j-1.6.1.jar
    ehcache-1.5.0.jar
    hibernate3.jar
    hibernate-annotations.jar
    hibernate-entirymanager.jar
    hibernate-jpa-2.0-api-1.0.0.Final.jar
    infinispan-core-4.0.0.FINAL.jar
    javassist-3.9.0.GA.jar
    jbosscache-core-3.2.1.GA.jar
    jta-1.1.jar
    oscache-2.1.jar
    proxool-0.8.3.jar
    slf4j-api-1.5.8.jar
    slf4j-nop-1.5.2.jar(注意这个包,一定要)
    swarmcache-1.0RC2.jar
数据库驱动包:
   mysql-connector-java-5.1.6-bin.jar
在src目录下建立META-INF,并且在该目录下建立一个persistence.xml文件

以上基本上就配置好开发环境了。
下面看看persistence.xml的文件
<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="test" transaction-type="RESOURCE_LOCAL" >
      <properties>
	      <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
	      <property name="hibernate.hbm2ddl.auto" value="update"/>
	      <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/> 
		<property name="hibernate.connection.url" value="jdbc:mysql://localhost/hibernate"/> 
		<property name="hibernate.connection.user" value="root"/> 
		<property name="hibernate.connection.password" value="123456"/> 
      </properties>
   </persistence-unit>
</persistence>

如果之前学过Hibernate的话,Properties里面的内容应该很清楚的,如果不清楚看了以上内容应该也很清楚。

这个 <persistence-unit name="test" transaction-type="RESOURCE_LOCAL" >就是体现JPA的东西了。什么意思呢?name这个先不说,待会看程序中的引用在来介绍。
transaction-type是事物类型。事物类型包括全局类型和本地类型。在不牵涉多个不同数据库的时候,一般使用本地事物。
下面给出一个Domain类
mport java.util.Date;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

@Entity //申明是一个实体,也就是实体
@Table(name="test_Person") //申明实体对应数据表的名字
public class Person {

	private Integer id;
	private String name;
	private Date birthday;
	private Gender gender = Gender.MAN; //设置默认值
	private String info;//大文本
	private Byte[] file; //字节数据
	private String imagepath; //该字段不持久化
	
	
	

	public Person(){}
	public Person(String name){
		this.name = name;

	}
	
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	public Integer getId() {
		return id;
	}

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

	@Temporal(TemporalType.DATE)
	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	

	@Column(length=10,nullable=false)
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	@Transient //不在数据表中生成一个imagepath字段
	public String getImagepath() {
		return imagepath;
	}
	public void setImagepath(String imagepath) {
		this.imagepath = imagepath;
	}

	@Lob 
	@Basic(fetch=FetchType.LAZY)//进行懒加载
	public Byte[] getFile() {
		return file;
	}
	public void setFile(Byte[] file) {
		this.file = file;
	}

	@Lob
	public String getInfo() {
		return info;
	}
	public void setInfo(String info) {
		this.info = info;
	}
}

在实体类中@xx表示的是标签。
下面 看看test类
import java.util.List;

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

import org.junit.BeforeClass;
import org.junit.Test;

import cn.itcast.domain.Person;

public class PersonTest {

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		
	}
	
  @Test public void save(){
	   EntityManagerFactory factory = Persistence.createEntityManagerFactory("test");//这里就是获取<persistence-unit name="test" >的name值
	   //-->sessionFactory ---> session --> begin事务
  	   EntityManager em = factory.createEntityManager();	  
  	   em.getTransaction().begin();//开始事务
 
	   em.persist(new Person("dave"));
	   em.getTransaction().commit();
	   em.close();
	   factory.close();
   }
  
   
  @Test public void getPerson(){
	   EntityManagerFactory factory = Persistence.createEntityManagerFactory("test");//这里就是获取<persistence-unit name="test" >的name值

	   EntityManager em = factory.createEntityManager();
	   Person person = em.find(Person.class,1);
System.out.println(person.getName());
	   em.close();
	   factory.close();
   
   }
   
  
   @Test public void getPerson2(){
	   EntityManagerFactory factory = Persistence.createEntityManagerFactory("test");");//这里就是获取<persistence-unit name="test" >的name值

	   EntityManager em = factory.createEntityManager();
	   Person person = em.getReference(Person.class,1); //延迟加载
System.out.println(person.getName());
	   em.close();
	   factory.close();
   
   }
   
   
        //新建状态
	    //托管状态 
	    //游离状态
	    //删除状态
   @Test public void UpdatePerson(){
	   EntityManagerFactory factory = Persistence.createEntityManagerFactory("test");
  	   EntityManager em = factory.createEntityManager();	  
  	   em.getTransaction().begin();//开始事务
  	 Person person = em.find(Person.class,1);
	   person.setName("江都西");
	   em.getTransaction().commit();
	   em.close();
	   factory.close(); 
   }
   
   
   @Test public void UpdatePerson2(){
	   EntityManagerFactory factory = Persistence.createEntityManagerFactory("test");
  	   EntityManager em = factory.createEntityManager();	  
  	   em.getTransaction().begin();//开始事务
  	   Person person = em.find(Person.class,1);
  	   
  	   em.clear();//把实体管理器中的所有实体变为游离状态
  	 person.setName("蒋笃淅");
	   em.merge(person); 
	   em.getTransaction().commit();
	   em.close();
	   factory.close(); 
   }
   
   
   @Test public void Delete(){
	   EntityManagerFactory factory = Persistence.createEntityManagerFactory("test");
  	   EntityManager em = factory.createEntityManager();	  
  	   em.getTransaction().begin();//开始事务
  	   Person person = em.find(Person.class,1);
  	   em.remove(person);
	   em.getTransaction().commit();
	   em.close();
	   factory.close(); 
   }
   
   
   @Test public void query(){
	    EntityManagerFactory factory = Persistence.createEntityManagerFactory("test");
	      EntityManager em = factory.createEntityManager();
	      Query query = em.createQuery("select o from Person o where o.id=?1");
	      query.setParameter(1, 2);
	     List<Person> person = query.getResultList();
	     for(Person p:person){
	 System.out.println(p.getName());
	     }
	    em.close();
	    factory.close(); 
	   }
	   
	   @Test public void deletequery(){
	    EntityManagerFactory factory = Persistence.createEntityManagerFactory("test");
	      EntityManager em = factory.createEntityManager();
	    em.getTransaction().begin();//开始事务
	      Query query = em.createQuery("Delete  from Person o where o.id=?1");
	      query.setParameter(1, 3);
	       query.executeUpdate();
	      em.getTransaction().commit();
	    em.close();
	    factory.close(); 
	   }
	   
	   @Test public void queryUpdate(){
	    EntityManagerFactory factory = Persistence.createEntityManagerFactory("test");
	      EntityManager em = factory.createEntityManager();
	     em.getTransaction().begin();//开始事务
	      Query query = em.createQuery("Update Person o set o.name=:name where o.id=:id");
	      query.setParameter("name", "蒋笃淅");
	      query.setParameter("id", 3);
	       query.executeUpdate();
	    em.getTransaction().commit();
	    em.close();
	    factory.close(); 
	   } 
}

以上基本上能够构建一个JPA开发环境并且基本的操作能够了解。至于配置一对多,多对一,多对多等将在后续给出学习比较和实现。

你可能感兴趣的:(Hibernate,mysql,jpa,JUnit,配置管理)