Maven + JPA + Hibernate + Postgresql的基本配置实例


一、创建项目

使用Maven或Eclipse插件m2eclipse创建Maven项目,在pom.xml添加依赖:


	UTF-8
	1.0.1.Final
	4.2.1.Final
	9.4-1201-jdbc41
	1.6.4
	4.11




	
	
		org.hibernate.javax.persistence
		hibernate-jpa-2.0-api
		${jpa.version}
	

	
	
		org.hibernate
		hibernate-entitymanager
		${hibernate.version}
	

	
	
		org.slf4j
		slf4j-log4j12
		${slf4j.version}
	

	
	
		org.postgresql
		postgresql
		${postgresql.version}
	

	
	
		junit
		junit
		${junit.version}
		test
	

二、配置persistence.xml

在src/main/resources下创建文件夹META-INF,新建XML文件,写上配置信息:


  
	
	
		
		org.hibernate.ejb.HibernatePersistence
		
		
			
			
			
			
			
			
			
			
			
			
			
			
		
	


三、创建实体对象

user(不分大小写)是Postgresql的保留字,故表名改为t_user

package com.hason.jpastudy.entity;

import java.io.Serializable;

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

@Entity
@Table(name = "t_user")
public class User implements Serializable{

	private static final long serialVersionUID = -8892552542169372174L;

	private Long id;

	private String name;
	
	private Integer age;

	@Id
	@GeneratedValue
	public Long getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}
	
}

三、编写主程序

package com.hason.jpastudy.jpa_2;

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

import com.hason.jpastudy.entity.User;

/**
 * 测试JPA
 *
 */
public class App {
	
	public static void main(String[] args) {
		
		String persistenceUnitName = "jpa-2";  // persistence.xml配置里的unit name,可以改变
		
		// 1.创建EntityManagerFactory
		EntityManagerFactory factory = Persistence.createEntityManagerFactory(persistenceUnitName);
		// 2.创建EntityManager
		EntityManager entityManager = factory.createEntityManager();
		// 3.创建、开启事务
		EntityTransaction transaction = entityManager.getTransaction();
		transaction.begin();
		// 4.进行持久化
		User user = new User();
		user.setName("hason");
		user.setAge(18);
		entityManager.persist(user);
		// 5.提交事务
		transaction.commit();
		// 6.关闭EntityManager
		entityManager.close();
		// 7.关闭EntityManagerFacoty
		factory.close();
	}
	
}


四、常见错误:

1、No Persistence provider for EntityManager named **: 原因可能是xml文件位置不不正确(没有正确引入XML)或unit name的名字不对

2、java.lang.NoSuchMethodError: javax.persistence.Table.indexes()[Ljavax/persistence/Index:Hibernate4.3版本中使用了@Table注解会出现此错误,解决方法之一:使用4.2或其他版本;其他方法百度谷歌





你可能感兴趣的:(JPA)