비 용기 환경 에서 OpenJPA 응용 프로그램 실행

주: 본인 은 인터넷 상의 관련 글 내용 을 참조 하여 썼 습 니 다.
1. 말 할 것 도 없 이 먼저 http://openjpa.apache.org 까지 OpenJPA 관련 가방 을 다운로드 합 니 다.
2.Animal.java
package com.openjpa.entity;

import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;


/**
 * Animal         Animal  ,      <br>
 * id -   ,    Oracle       <br>
 * name - Animal   
 */
/* Entity           , name                 ,      */
@Entity
public class Animal {
	//   
	@Basic
	private String name;

	//   
	/* Id             */
	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="SEQ_ANIMAL")
	@SequenceGenerator(name="SEQ_ANIMAL", sequenceName="SEQ_ANIMAL")
	private int id;

	public int getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

}

 AnimalDAO.java
package com.openjpa.dao;

import java.util.List;

import com.openjpa.entity.Animal;

/**
 * @author king
 * 
 */
public interface AnimalDAO {
	/**
	 *     Animal  
	 * 
	 * @param animal
	 *              Animal  
	 */
	public void persistAnimal(Animal animal);

	/**
	 *   Animal     
	 * 
	 * @param animal
	 *                Animal  
	 */
	public void updateAnimal(Animal animal);

	/**
	 *   Animal  
	 * 
	 * @param id
	 *                Animal  
	 */
	public void removeAnimal(int id);

	/**
	 *   id       Animal
	 * 
	 * @param id
	 *            animal   
	 * @return      id Animal  
	 */
	public Animal getAnimalByPrimaryKey(int id);

	/**
	 *                      Animal    
	 * 
	 * @param name
	 *            Animal    
	 * @return      Animal    
	 */
	public List<Animal> findAnimalsByName(String name);

}

 AnimalDAOImpl.java
package com.openjpa.impl.ejb3;

import java.util.List;

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

import com.openjpa.dao.AnimalDAO;
import com.openjpa.entity.Animal;

/**
 * AnimalDAOImpl        OpenJPA           
 * 
 * @author king
 * 
 */
public class AnimalDAOImpl implements AnimalDAO {

	
	/**
	 * removeAnimal                Animal  
	 * 
	 * @param id
	 *            Animal     
	 */
	public void removeAnimal(int id) {
		//   EntityManagerFactory
		EntityManagerFactory factory = Persistence
				.createEntityManagerFactory("oracle");
		//   EntityManager
		EntityManager em = factory.createEntityManager();
		//       
		em.getTransaction().begin();

		//   Query    
		em.createQuery("delete from Animal animal where animal.id=" + id)
				.executeUpdate();

		//               
		/*
		 * //  EntityManager            Animal animal =
		 * em.find(Animal.class,id); //   EntityManager remove      
		 * em.remove(animal);
		 */

		//     
		em.getTransaction().commit();
		//   EntityManager
		em.close();
		//   EntityManagerFactory
		factory.close();

	}

	/**
	 * findAnimalsByName      name           Animal    
	 * 
	 * @param name
	 *            Animal   name
	 * @return          Animal    
	 */
	public List<Animal> findAnimalsByName(String name) {
		//   EntityManagerFactory
		EntityManagerFactory factory = Persistence
				.createEntityManagerFactory("oracle");
		//   EntityManager
		EntityManager em = factory.createEntityManager();

		/*
		 *   EntityManager createQuery    Query  
		 * createQuery      JPQL    ,JPQL        OpenJPA     .
		 * 
		 *             ,  Query         begin、commit     
		 * 
		 */
		 Query q = em.createQuery("select animal from Animal animal where animal.name like :name");
		q.setParameter("name", "%" + name + "%");
		List<Animal> l = q.getResultList();
		//   EntityManager
		em.close();
		//   EntityManagerFactory
		factory.close();

		return l;
	}

	/**
	 * getAnimalByPrimaryKey              Animal  ,        Animal     null
	 * 
	 * @param id
	 *            Animal     
	 * @return        Animal  
	 * 
	 */
	public Animal getAnimalByPrimaryKey(int id) {
		//   EntityManagerFactory
		EntityManagerFactory factory = Persistence
				.createEntityManagerFactory("oracle");
		//   EntityManager
		EntityManager em = factory.createEntityManager();

		//          
		Animal animal = em.find(Animal.class, id);

		//   EntityManager
		em.close();
		//   EntityManagerFactory
		factory.close();

		return animal;
	}

	/**
	 *            
	 * 
	 * @param animal
	 *                     
	 */
	public void persistAnimal(Animal animal) {
		//   EntityManagerFactory
		EntityManagerFactory factory = Persistence
				.createEntityManagerFactory("oracle");
		//   EntityManager
		EntityManager em = factory.createEntityManager();
		//       
		em.getTransaction().begin();

		//      
		em.persist(animal);

		//     
		em.getTransaction().commit();
		//   EntityManager
		em.close();
		//   EntityManagerFactory
		factory.close();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.vivianj.openjpa.AnimalDAO#updateAnimal(org.vivianj.openjpa.entity.Animal)
	 */
	public void updateAnimal(Animal animal) {
		//   EntityManagerFactory
		EntityManagerFactory factory = Persistence
				.createEntityManagerFactory("oracle");
		//   EntityManager
		EntityManager em = factory.createEntityManager();
		//       
		em.getTransaction().begin();

		//      
		em.merge(animal);

		//     
		em.getTransaction().commit();
		//   EntityManager
		em.close();
		//   EntityManagerFactory
		factory.close();

	}

}

 3.persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    version="1.0">
    <persistence-unit name="oracle" transaction-type="RESOURCE_LOCAL">
        <provider>
            org.apache.openjpa.persistence.PersistenceProviderImpl
        </provider>
        
        <class>com.openjpa.entity.Animal</class>

        <properties>
            <property name="openjpa.ConnectionURL" value="jdbc:oracle:thin:@192.168.1.8:1521:test"/>
            <property name="openjpa.ConnectionDriverName" value="oracle.jdbc.OracleDriver"/>
            <property name="openjpa.ConnectionUserName" value="test"/>
            <property name="openjpa.ConnectionPassword" value="test"/>
            <property name="openjpa.Log" value="SQL=TRACE"/>
        </properties>
    </persistence-unit>
</persistence>

 4. 본인 이 사용 하 는 것 은 Oracle, Animal 표 의 id 는 자체 증가 서열 입 니 다. 시작 하기 전에 저 희 는 데이터 베이스 에서 좋 은 서열 을 만 들 수 있 습 니 다.
create sequence seq_animal
minvalue 1
start with 1
increment by 1;

  데이터베이스 테이블 은 명령 행 방식 으로 생 성 할 수 있 습 니 다:
java org.apache.openjpa.jdbc.meta.MappingTool Animal.java

  5. TestAnimal DaoImpl. java 테스트 를 실행 하면 다음 효 과 를 볼 수 있 습 니 다.
package test.openjpa;

import java.util.List;

import com.openjpa.entity.Animal;
import com.openjpa.impl.ejb3.AnimalDAOImpl;

public class TestAnimalDaoImpl {
	
	public static void main(String[] args) {
		
		AnimalDAOImpl animalDaoImpl = new AnimalDAOImpl();
		
		//  
		Animal a = new Animal();
		a.setName("  openJPA");
		animalDaoImpl.persistAnimal(a);
		
		//  
		List<Animal> animals = animalDaoImpl.findAnimalsByName("open");
		for(Animal animal: animals){
			System.out.println("name = " + animal.getName());
		}
		
		//    
		Animal an = animalDaoImpl.getAnimalByPrimaryKey(a.getId());
		System.out.println("Aniaml id = " + a.getId() + " , name = " + an.getName());
		
		
		//  
		animalDaoImpl.removeAnimal(a.getId());
		
		//  
		animals = animalDaoImpl.findAnimalsByName("open");
		for(Animal animal: animals){
			System.out.println("name = " + animal.getName());
		}
		
	}

}

좋은 웹페이지 즐겨찾기