JPA 中的CRUD操作

直接上代码了:

package com.dimples.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import org.junit.Test;

import com.dimples.dao.Customer;

public class JustTest {
	//新增一条记录
	@Test
	public void test() {
		Customer c = new Customer();
		c.setName("zhangsan");
		c.setLevel("3");
		EntityManager em = MyJPAUtils.getEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		em.persist(c);
		tx.commit();
		em.close();
	}
	
	//查询
	@Test
	public void testQuery() {
		EntityManager em = MyJPAUtils.getEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		Customer c = em.find(Customer.class, Integer.parseInt("1"));//单行查询
		System.out.println(c);
		//多行查询,这里的占位符是这样的形式 ?1  ?2  ?3,而有的版本直接是 ? ? ?,略微有点差异,注意一下
		Query query = em.createQuery("select c from Customer c where id > ?1");
		//这里设置参数的时候和hibernate也不太一样,这没有setString等方法,只有下面这一个方法。
		//且hibernate中后面那个参数可以直接写String它后面会帮我们自动转化,但这里必须跟自己但参数类型对应上,否则会报错。
		//这里的参数下标是从1开始的,HQL语句从0开始的
		query.setParameter(1, Integer.parseInt("0"));
		List<Object> lists = query.getResultList();
		for(Object o : lists) {
			System.out.println(o);
		}
		tx.commit();
		em.close();
	}
	
	//更新
	@Test
	public void testMerge() {
		EntityManager em = MyJPAUtils.getEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		Customer c = em.find(Customer.class, Integer.parseInt("1"));
		c.setAddress("家里蹲");
		em.merge(c);
		tx.commit();
		em.close();
	}
	
	//删除
	@Test
	public void testRemove() {
		EntityManager em = MyJPAUtils.getEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		Customer c = em.find(Customer.class, Integer.parseInt("1"));
		em.remove(c);
		tx.commit();
		em.close();
	}
	
}

猜你喜欢

转载自blog.csdn.net/dimples_qian/article/details/80895198