jpa的了解

1 jpa对hibernate编程所需要引入的包:

 

  hibernate-distribution中的(8个文件):hibernate3.jar  lib/bytecode/cglib/hibernate-cglib-repack-2.1-3.jar lib/required/*.jar

  hibernate-annotations中的(3个文件):hibernate-annotations.jar  lib/ejb3-persistance.jar  hibernate-commons-annotations.jar

  hibernate-entitymanager中的(3个文件):hibernate-entitymanager.jar  lib/test/log4j.jar  slf4j-log4j12.jar

 

2 jpa的配置文件persistent.xml 一定要这个名字。并且要把它放到类路径的META-INF目录下面

 

使用领域建模思想编写jpa的helloworld文件

  第一步:

  建立一个普通的java工程文件。导入jpa对应hibernate的jar包

  加入数据库的驱动

 第二步:

  在类路径下加入META-INF 下加入persistent.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="sample"  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.username" value="root"/>
         <property name="hiberante.connection.password" value="root	"/>
         <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/itcast?useUnicode=true&amp;characterEncoding=UTF-8"/>
      </properties>
   </persistence-unit>
</persistence>

 

第三步:

 书写实体bean

采用注解的方式来进行编写

 

package com.hust;

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

@Entity
public class Person {
	private Integer personId;
	private String psersonName;
	
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	public Integer getPersonId() {
		return personId;
	}
	public void setPersonId(Integer personId) {
		this.personId = personId;
	}
	public String getPsersonName() {
		return psersonName;
	}
	public void setPsersonName(String psersonName) {
		this.psersonName = psersonName;
	}
	
	
}

 第四步:

 书写junit测试

 

package com.hust;

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

import org.junit.Test;


public class PersonTest {
	@Test
	public void save(){
		//首先获得factory然后获得session,在然后打开事物
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("sample");
		/*EntityManager em = factory.createEntityManager();
		em.getTransaction().begin();//获得事物
		Person p = new Person();
		p.setPsersonName("孙启堂");
		em.persist(p);
		em.getTransaction().commit();
		em.close();
		factory.close();*/
		factory.close();
		System.out.println("Over");
	}
}
 

你可能感兴趣的:(Hibernate,xml,mysql,jpa,JUnit)