`
JavaCrazyer
  • 浏览: 3008797 次
  • 性别: Icon_minigender_1
  • 来自: 河南
社区版块
存档分类

Hibernate温习(8)--使用JPA

阅读更多

这次讲的JPA前一篇文章都有所介绍,这里呢就是结合hibernate.cfg.xml来讲讲,怎么用JPA进行CURD操作,类似于Hibernate的session进行CURD操作


hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
	<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
	<property name="connection.url">jdbc:mysql:///test</property>
	<property name="connection.username">root</property>
	<property name="connection.password">root</property>

	<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

	<property name="connection.isolation">2</property>

	<property name="show_sql">true</property>
	
	<property name="hbm2ddl.auto">update</property>
	
	<property name="format_sql">true</property>

	<!-- mapping类声明-->
	
	<mapping class="com.javacrazyer.domain.User" />
	
</session-factory>
</hibernate-configuration>

 
 JPA使用要求SRC的META-INF下要有persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
	<!-- example of a default 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="xkkjpa">
		<properties>
			<property name="hibernate.ejb.cfgfile" value="/hibernate.cfg.xml" />
		</properties>
	</persistence-unit>
</persistence>

 Hibernate这里用到的实体类映射是采用的是注解方式,其实就是JPA的注解

User.java

package com.javacrazyer.domain;

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

@Entity
@Table(name="user")
public class User {
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private Long id;
	
	private String name;
	private String pwd;
	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 String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	
	public String toString(){
		return "id=" + id + ",name=" + name + ",pwd=" + pwd;
	}
}

 UserDao.java

package com.javacrazyer.dao;

import java.util.List;

import javax.persistence.EntityManager;

import com.javacrazyer.common.JPAUtil;
import com.javacrazyer.domain.PageModel;
import com.javacrazyer.domain.User;


public class UserDao {
	
	public void add(User user){
		EntityManager em = JPAUtil.getEntityManager();
		em.getTransaction().begin();
		
		em.persist(user);
		
		em.getTransaction().commit();
		em.close();
	}
	
	@SuppressWarnings("unchecked")
	public List<User> findAll(){
		EntityManager em = JPAUtil.getEntityManager();
		em.getTransaction().begin();
		//JPAQL
		List<User> users = em.createQuery("from User").getResultList();
		
		em.getTransaction().commit();
		em.close();
		
		return users;
	}
	
	@SuppressWarnings("unchecked")
	public PageModel<User> findByPager(int pageNo, int pageSize){
		PageModel<User> pm = new PageModel<User>();
		
		EntityManager em = JPAUtil.getEntityManager();
		em.getTransaction().begin();
		
		Long count = (Long)em.createQuery("select count(o) from User o").getSingleResult();
		
		if(count != null){
		List<User> users = em.createQuery("from User")
							 .setFirstResult((pageNo - 1) * pageSize)
							 .setMaxResults(pageSize)
							 .getResultList();
			pm.setRecordCount(count.intValue());
			pm.setDatas(users);
		}
		em.getTransaction().commit();
		em.close();
		
		return pm;
	}
	
	public User findById(Long id){
		EntityManager em = JPAUtil.getEntityManager();
		em.getTransaction().begin();
		
		//User user = em.find(User.class, id);  //相当于Hibernate的get()方法
		User user = em.getReference(User.class, id); //相当于Hibernate的load()方法
		
		em.getTransaction().commit();
		em.close();
		
		return user;
	}
	
	public void update(User user){
		EntityManager em = JPAUtil.getEntityManager();
		em.getTransaction().begin();
		user = em.merge(user);
		
		em.getTransaction().commit();
		em.close();
	}
	
	public void delete(User user){
		EntityManager em = JPAUtil.getEntityManager();
		em.getTransaction().begin();
		
		em.remove(user);
		
		em.getTransaction().commit();
		em.close();
	}
}

 PageModel.java

package com.javacrazyer.domain;

import java.util.List;

/**
 * 分页组件(包含当前页结果数据列表和总记录数)
 * 注意,它不是持久化实体类
 * 
 */
public class PageModel<T> {
	private int recordCount;
	private List<T> datas;
	
	
	public int getRecordCount() {
		return recordCount;
	}
	public void setRecordCount(int recordCount) {
		this.recordCount = recordCount;
	}
	public List<T> getDatas() {
		return datas;
	}
	public void setDatas(List<T> datas) {
		this.datas = datas;
	}
}

 JPAUtil.java

package com.javacrazyer.common;

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


public class JPAUtil {
	  private static EntityManagerFactory factory;
	  static {
		  //加载src/META-INF/PERSISTENTCE.XML ,根据配置文件中的键加载
	    factory = Persistence.createEntityManagerFactory("xkkjpa");
	  }
	  private JPAUtil() {}

	  public static EntityManager getEntityManager() {
	    return factory.createEntityManager();
	  }

}

 测试代码

package com.javacrazyer.dao.test;

import org.junit.Assert;
import org.junit.Test;

import com.javacrazyer.dao.UserDao;
import com.javacrazyer.domain.PageModel;
import com.javacrazyer.domain.User;

public class UserDaoTest {
	private UserDao dao = new UserDao();
	
	@Test
	public void testAdd(){
		User user = new User();
		
		user.setName("xxxx");
		user.setPwd("12345678790");
		
		dao.add(user);
		
		Assert.assertNotNull(user.getId());
	}
	
	@Test
	public void testFindByPager(){
		PageModel<User> pm = dao.findByPager(2, 1);
		
		for(User user : pm.getDatas()){
			System.out.println(user);
		}
	}
}

 根据JPA对实体类进行CRUD的操作特点与Hibernate的处理方式做下对比

 Hibernate处理方式为:通过SessionFactory获得session,然后通过session的各种方法进行CURD操作

 JPA的处理方式为:通过EntityManagerFactory获得entityManager,然后通过entityManager的各种方法进行CURD

Hibernate是SessionFacotory sessionFactory=config.buidSessionFacotory()

JPA是EntityManagerFactory entityManagerFactory=Persistence.createEntityManagerFactory("xkkjpa");


hibernate是Session session=sessionFactory.openSesion()

JPA是EntityManager entityManager=factory.createEntityManager()

session的增删改查为save,delete,update,merge,createQuery()

entityManager的增删改为persist,remove,merge,createQuery


 

  • 大小: 8.6 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics