1. 程式人生 > >j2se環境jpa的實現和簡單動態切換資料來源

j2se環境jpa的實現和簡單動態切換資料來源

        專案中持久層用的eclipselink,有個需求是動態切換資料來源,首先做了個demo,先在j2se的環境中實現,然後再嘗試加到專案中。

        1、建立jpa專案,建立環境,建立eclipselink的user library,用於jpa專案

           

        2、建立jpa專案,將上一步建立的user library加入專案:

      

     3、建立專案結構:

      

     MyDao是建立jpa中的entitymanager物件的,Student是使用的實體,persistence.xml配置了持久化的屬性

      4、persistence.xml:

    配置了persistence-unit,事務策略、持久化的provider、持久化的class、資料來源屬性。

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
	<persistence-unit name="unit" transaction-type="RESOURCE_LOCAL"	>
		<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
       
        <span style="white-space:pre">	</span><class>com.tgb.jpa.entity.Student</class>  
		<properties>
			<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />  
            <span style="white-space:pre">		</span><property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpa1?useUnicode=true&characterEncoding=UTF-8" />  
            <span style="white-space:pre">		</span><property name="javax.persistence.jdbc.user" value="root" />  
            <span style="white-space:pre">		</span><property name="javax.persistence.jdbc.password" value="root" />  
            <span style="white-space:pre">		</span><property name="eclipselink.ddl-generation" value="drop-and-create-tables" />  
            <span style="white-space:pre">		</span><property name="eclipselink.ddl-generation.output-mode" value="both" /> 
			<property name="eclipselink.logging.level.sql" value="FINE"/>
		</properties>
	</persistence-unit>
</persistence>

    5、MyDao.java:

package com.tgb.jpa.dao;

import java.util.HashMap;
import java.util.Map;

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


public class MyDao {
	//定義工廠
	private EntityManagerFactory emf;
	//定義entitymanager
	private EntityManager em;
	//獲取EntityManager的方法,根據有沒有傳入url建立不同策略的EntityManager
	public EntityManager getEntityManager(String url){
		//採用persitence.xml中的預設配置
		if (url==""||url==null) {
			emf=Persistence.createEntityManagerFactory("unit");
			em=emf.createEntityManager();
		}else {
			//更改url屬性
			Map<String, String> properties =new HashMap<String, String>();
			properties.put("javax.persistence.jdbc.url","jdbc:mysql://"+url);
			emf = Persistence.createEntityManagerFactory("unit", properties);
			
			em=emf.createEntityManager();
		}
		return em;
	}
	
	public EntityManager getEntityManager(){
		return getEntityManager(null);
	}
}

         6、Student實體:
package com.tgb.jpa.entity;

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

@Entity
@Table(name="t_student")
public class Student {

	private String id;
	
	private String name;
	
	private String sex;
	
	private String addr;

	@Id
	public String getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getAddr() {
		return addr;
	}

	public void setAddr(String addr) {
		this.addr = addr;
	}
	
}

     7、測試類Client:
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import org.junit.Test;

import com.tgb.jpa.dao.MyDao;
import com.tgb.jpa.entity.Student;

public class Client {

	@Test
	public void testJpa1() {
		MyDao dao=new MyDao();
		//根據persistence.xml配置建立em
		EntityManager entityManager=dao.getEntityManager();
		
		EntityTransaction transaction= (EntityTransaction) entityManager.getTransaction();
		try {

				// 開始事務
				transaction.begin();
				
				Student student=new Student();
				student.setId("1");
				student.setAddr("hebei");
				student.setName("tom");
				student.setSex("men");
				
				
				entityManager.persist(student);
				// 提交事務
				transaction.commit();

			} catch (Exception e) {
				// 事務回滾
				transaction.rollback();
				e.printStackTrace();
			}finally{
				if (entityManager.isOpen()) {
					entityManager.getEntityManagerFactory().close();
				}
			}
	}	
	
	@Test
	public void testJpa2 (){
		MyDao dao=new MyDao();
		//傳入url屬性,改變emFactory的屬性
		EntityManager entityManager=dao.getEntityManager("localhost:3306/jpa2");
		EntityTransaction transaction= (EntityTransaction) entityManager.getTransaction();
		try {

				// 開始事務
				transaction.begin();
				
				Student student=new Student();
				student.setId("2");
				student.setAddr("beijing");
				student.setName("jerry");
				student.setSex("women");
				
				entityManager.persist(student);
				// 提交事務
				transaction.commit();

			} catch (Exception e) {
				// 事務回滾
				transaction.rollback();
				e.printStackTrace();
			}finally{
				if (entityManager.isOpen()) {
					entityManager.getEntityManagerFactory().close();
				}
			}
	}
}

testJpa1()是讀取persistence.xml配置檔案的屬性,就是預設的,執行後資料庫新增一條資料:


jpa1庫:


testJpa2是傳入了url,並且根據這個屬性改變了EntityManagerFactory的屬性,所以連線字串就變成了傳入的jpa2資料庫,所以testJpa2的資料新增到了jpa2庫中:


這樣就完成了jpa的實現,並且簡單實現了切換資料庫的需求。