我正在使用swing和JPA创建项目,它工作正常,但现在我想更改此项目以使用JPA而不使用persistence.xml文件。我正在寻找一些例子,但仍未找到任何解决方案。我知道春天已经走了,但我不知道。
有某种方法可以做到这一点,怎么办?
答案 0 :(得分:0)
我解决了这个问题。 JPA始终需要persistence.xml
,但我可以创建一个简单的persistence.xml
设置只有一个persistence-unit
,之后我可以创建一个类来定义连接值和其他值。
这里是persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" 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_2_0.xsd">
<persistence-unit name="default">
<exclude-unlisted-classes>false</exclude-unlisted-classes>
</persistence-unit>
</persistence>
,这里是我设置值的类
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.PersistenceUnitTransactionType;
import org.eclipse.persistence.jpa.PersistenceProvider;
import org.eclipse.persistence.config.PersistenceUnitProperties;
/**
*
* @author fernando
*/
public class JPAUtils {
private static EntityManagerFactory emf;
private static final String PERSISTENCE_UNIT = "default";
private static final String DB_NAME = "iguanaauto_db";
public static String IP_SERVER = "127.000.000.001";
/** return an entitymanagerfactory */
public static EntityManagerFactory getEntityManagerFactory(){
if(emf == null){
PersistenceProvider pp = new PersistenceProvider();
Map<String, String> properties = new HashMap<String, String>();
properties.put(PersistenceUnitProperties.TRANSACTION_TYPE, PersistenceUnitTransactionType.RESOURCE_LOCAL.name());
properties.put(PersistenceUnitProperties.JDBC_DRIVER, "com.mysql.jdbc.Driver");
properties.put(PersistenceUnitProperties.JDBC_URL, "jdbc:mysql://" + IP_SERVER + ":3306/" + DB_NAME + "?createDatabaseIfNotExist=true");
properties.put(PersistenceUnitProperties.JDBC_USER, "root");
properties.put(PersistenceUnitProperties.JDBC_PASSWORD, "");
properties.put(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.CREATE_OR_EXTEND);
properties.put(PersistenceUnitProperties.DDL_GENERATION_MODE, PersistenceUnitProperties.DDL_DATABASE_GENERATION);
properties.put(PersistenceUnitProperties.LOGGING_LEVEL, "FINE");
emf = pp.createEntityManagerFactory(PERSISTENCE_UNIT, properties);
}
return emf;
}
}