论坛首页 Java企业应用论坛

JPA完成对数据库的单表基本操作

浏览 3111 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (1) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-10-12   最后修改:2009-10-12

1,实体Bean配置如下:

package com.mengya.bean;

import java.util.Date;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

import com.mengya.util.Gender;

//表示实体Bean
@Entity
//设置表名
@Table(name = "PERSON")
public class Person {

	private Integer id;

	private String name;

	private Date birthday;
	
	private String info;
	
	private byte[] file;
	
	private String imagePath;
	
	// 枚举类型
	// 设置该列的默认值,在字段后面赋初始值
	private Gender sex = Gender.MAN;

	public Person() {

	}
	public Person(String name) {
		this.name = name;
	}

	// 放在get方法上面或字段上面
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	public Integer getId() {
		return id;
	}

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

	// 设置该列在数据中列名,长度,非空
	@Column(name = "p_name", length = 10, nullable = false)
	public String getName() {
		return name;
	}

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

	// 设置日期的格式为yyyy-MM-dd
	@Temporal(TemporalType.DATE)
	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	// 取其枚举的值
	@Enumerated(EnumType.STRING)
	// 取其枚举的索引
	// @Enumerated(EnumType.ORDINAL);
	@Column(length = 10, nullable = false)
	public Gender getSex() {
		return sex;
	}

	public void setSex(Gender sex) {
		this.sex = sex;
	}
	
	//@Lob表示大的文本字段
	//@Basic(fetch=FetchType.LAZY)设置该字段是否懒加载
	@Lob @Basic(fetch=FetchType.LAZY)
	public String getInfo() {
		return info;
	}

	public void setInfo(String info) {
		this.info = info;
	}
	
	//大的二进制字段
	@Lob
	public byte[] getFile() {
		return file;
	}

	public void setFile(byte[] file) {
		this.file = file;
	}
	
	//非持久化字段(数据库中没有字段与之对应)
	@Transient
	public String getImagePath() {
		return imagePath;
	}

	public void setImagePath(String imagePath) {
		this.imagePath = imagePath;
	}

}

 

数据库操作如下:

 

package junit.test;


import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

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

import org.junit.BeforeClass;
import org.junit.Test;

import com.mengya.bean.Person;
import com.mengya.util.Gender;

public class PersonTest {

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}
	
	@Test public void save(){
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("mengya");
		EntityManager manager=factory.createEntityManager();
		manager.getTransaction().begin();
		
		Person p=new Person();
		p.setName("小酱油");
		DateFormat df=DateFormat.getDateInstance();
		try {
			Date d=df.parse("1986-8-25");
			p.setBirthday(d);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		p.setSex(Gender.WOMAN);
		
		manager.persist(p);
		
		manager.getTransaction().commit();
		manager.close();
		factory.close();
	}
	
	@Test public void getPerson(){
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("mengya");
		EntityManager manager=factory.createEntityManager();
		//类似Hibernate中的get方法
		Person p=manager.find(Person.class, 2);
		System.out.println(p.getId() + p.getName() + p.getSex());
		manager.close();
		factory.close();
	}
	
	@Test public void getPerson2(){
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("mengya");
		EntityManager manager=factory.createEntityManager();
		//类似Hibernate中的load方法,没有真正的访问数据库,返回的只是一个代理对象
		//若在manager.close()之前没有访问p对象而是在它之后访问p对象的属性则会出错
		Person p=manager.getReference(Person.class, 2);
		System.out.println(p.getName());//这个时候才真正的访问数据库加载数据
		manager.close();
		factory.close();
	}
	
	@Test public void updatePerson(){
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("mengya");
		EntityManager manager=factory.createEntityManager();
		manager.getTransaction().begin();
		//由于处于托管状态并且处于事务当中故当事务提交时与数据库同步
		Person p=manager.find(Person.class, 2);
		p.setName("梦娅");
		manager.getTransaction().commit();
		manager.close();
		factory.close();
	}
	
	@Test public void updatePerson2(){
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("mengya");
		EntityManager manager=factory.createEntityManager();
		manager.getTransaction().begin();
		Person p=manager.find(Person.class, 3);
		manager.clear();//clear方法使p由托管状态变成游离状态
		p.setName("张明学");
		manager.merge(p);//merge方法将实体对象与数据库同步
		manager.getTransaction().commit();
		manager.close();
		factory.close();
	}
	
	@Test public void deletePerson(){
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("mengya");
		EntityManager manager=factory.createEntityManager();
		manager.getTransaction().begin();
		Person p=manager.find(Person.class, 2);
		//Person p=manager.getReference(Person.class, 2);
		manager.remove(p);
		manager.getTransaction().commit();
		manager.close();
		factory.close();
	}
	
	//单个查询
	@Test public void query(){
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("mengya");
		EntityManager manager = factory.createEntityManager();
		String querySql="select p from Person p where p.id=?1";
		Query query=manager.createQuery(querySql);
		query.setParameter(1, 1);
		Person p=(Person) query.getSingleResult();
		System.out.println(p.getName());
		manager.close();
		factory.close();
	}
	
	//批量查询
	@Test public void queryAll(){
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("mengya");
		EntityManager manager=factory.createEntityManager();
		String querySql = "select p from Person p";
		Query query=manager.createQuery(querySql);
		List<Person> personList=query.getResultList();
		for(Person p:personList){
			System.out.println(p.getName());
		}
		manager.close();
		factory.close();
	}
	
	@Test public void updateQuery(){
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("mengya");
		EntityManager manager = factory.createEntityManager();
		manager.getTransaction().begin();
		String querySql = "update Person p set p.name=:name where p.id=:id";
		Query query=manager.createQuery(querySql);
		query.setParameter("name", "梦娅");
		query.setParameter("id", 1);
		query.executeUpdate();
		manager.getTransaction().commit();
		manager.close();
		factory.close();
	}
	
	@Test public void deleteQuery(){
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("mengya");
		EntityManager manager = factory.createEntityManager();
		manager.getTransaction().begin();
		String querySql = "delete Person where id=:id";
		Query query=manager.createQuery(querySql);
		query.setParameter("id", 1);
		query.executeUpdate();
		manager.getTransaction().commit();
		manager.close();
		factory.close();
	}
	
}

 

  • JPA_Dome.rar (9.9 KB)
  • 描述: 我的例实
  • 下载次数: 118
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics