JPA(一)之入门实例

1.准备阶段:

    (1)jar包: JPA(一)之入门实例

 

 2. 建好项目后,将persistence.xml放在如下位置:

    JPA(一)之入门实例

      代码如下:

<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="unitname" transaction-type="RESOURCE_LOCAL">
      <properties>
         <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
         <property name="hibernate.connection.driver_class" value="org.gjt.mm.mysql.Driver"/>
         <property name="hibernate.connection.username" value="root"/>
         <property name="hibernate.connection.password" value="beanGou"/>
         <property name="hibernate.connection.url" 
         value="jdbc:mysql://localhost:3306/jpa_practice?useUnicode=true&amp;characterEncoding=UTF-8"/>
         <property name="hibernate.hbm2ddl.auto" value="update"/>
      </properties>
   </persistence-unit>
</persistence>


   注意配置文件中的value,尤其是url....

3.进行单元测试:

  JPA(一)之入门实例

   代码如下:

 

package junit.test;

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

import org.junit.Test;

import com.sonoi.bean.Person;

public class PerTest {

	@Test
	public void save() {
		EntityManagerFactory factory = Persistence
				.createEntityManagerFactory("unitname");
		EntityManager manager = factory.createEntityManager();
		manager.getTransaction().begin();
		//不能输入汉字!针对my操作系统
		manager.persist(new Person("nansheng"));
		manager.getTransaction().commit();
		manager.close();
		factory.close();
	}
}


然后直接运行PerTest的save方法即可!

 

你可能感兴趣的:(JPA学习进阶)