Hibernate中使用JPA(注解)配置对象关系映射

java中注解也是一大特点,平时进行单元测试时我们用过@Test注解进行测试

JPA就是java专门针对持久层框架进行设计的一套规范

JPA:Java Persistence API,其实它也就是一堆接口,就想JDBC一样,不同的框架只要遵循这同一套规范就可以在java环境中使用。

我们都指定在使用Hibernate的时候我们要写很多的.xml配置文件,xxx.hbm.xml对象关系映射文件,hibernate.cfg.xml核心配置文件

JPA就是利用注解代替了xxx.hbm.xml这些映射文件,hibernate.cfg.xml这个核心配置文件在JPA这套规范中也换了名字,但是做的事情是差不多的

先看看JPA是怎么使用注解代替映射文件的


@Entity
@Table(name="t_customer")
public class Customer{
				
	@Id
	@Column(name="cust_id")
	@GenericGenerator(name="sysnative",strategy="native")
	@GeneratedValue(generator="sysnative")
	private Long custId;
	@Column(name="cust_name")
	private String custName;
	@Column(name="cust_sex")
	private String custSex;
				
}

Hibernate中使用JPA(注解)配置对象关系映射_第1张图片


核心配置文件:

之前的Hibernate核心配置文件时hibernate.cfg.xml


	
	
		
		com.mysql.jdbc.Driver
		jdbc:mysql:///ssh
		root
		root
		
		org.hibernate.dialect.MySQLDialect
		
		true
		true
		none
		
		org.hibernate.connection.C3P0ConnectionProvider
		
		thread
		
		
	

在JPA中的核心配置文件是 persistence.xml,而且它的存放位置也不一样,它的存放位置是src/META-INF/persistence.xml,而且名字必须是persistence.xml

persistence.xml 的内容



	
	
	
		
		org.hibernate.jpa.HibernatePersistenceProvider
		
		
		
			
			
			
			
			
			
			
			
			
			
			
			
			
		
	
  

Hibernate中使用JPA(注解)配置对象关系映射_第2张图片


在JPA中的对象操作的API也有所不同

在之前Hibernate中,使用SessionFactory来创建Session,使用Session创建事务操作数据库

在JPA中,使用的是

EntityManagerFactory emFactory = Persistence.createEntitiyManagerFactory("myPersistence");//是核心配置文件中的name值

EntityManager em = emFactory.createEntityManager();

/**
	 * 单表添加
	 */
	public void addPer(){
		EntityManager em = EntityManagerFactoryUtil.createEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		Person p = new Person();
		p.setUname("哈哈哈");
		em.persist(p);
		tx.commit();
	}


/**
	 * 单表查询
	 */
	public void getPer(){
		EntityManager em = EntityManagerFactoryUtil.createEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		Person person = em.find(Person.class, 1);
		System.out.println(person);
		tx.commit();
	}


/**
	 * 单表更新
	 */
	public void updatePer(){
		EntityManager em = EntityManagerFactoryUtil.createEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		Person person = em.find(Person.class, 1);
		person.setUname("呵呵呵");
		tx.commit();
	}

数据操作其实和HQL查询方式中大致语法差不多


你可能感兴趣的:(SSH框架,JPA)