我尝试将这些值插入持久性类 但我不能,我也不知道为什么 我已经尝试了很多事情,并且浪费了很多时间,却没有得到任何结果:'( 我在JPA JSF中是菜鸟
实体课程
package testes;
import entity.Automovel;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
public class PersistidorDeAutomovel {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.
createEntityManagerFactory("default");
EntityManager em = JPAUtil.getEntityManager();
Automovel auto = new Automovel();
auto.setAnoFabricacao(2010);
auto.setModelo("Ferrari");
auto.setObservacoes("Nunca foi batido");
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(auto);
tx.commit();
em.close();
emf.close();
}
}
JPAUtil类
package testes;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class JPAUtil {
private static final EntityManagerFactory emf =
Persistence.createEntityManagerFactory("default");
public static EntityManager getEntityManager() {
return emf.createEntityManager();
}
}
持久性测试类,只要可以将数据插入数据库中,就可以创建它进行测试。我只是不明白为什么它不起作用
package testes;
import entity.Automovel;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
public class PersistidorDeAutomovel {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.
createEntityManagerFactory("default");
EntityManager em = JPAUtil.getEntityManager();
Automovel auto = new Automovel();
auto.setAnoFabricacao(2010);
auto.setModelo("Ferrari");
auto.setObservacoes("Nunca foi batido");
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(auto);
tx.commit();
em.close();
emf.close();
}
}
持久性类配置
<?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="default" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>entity.Automovel</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/automovel?zeroDateTimeBehavior=convertToNull"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value="1q2w3e4r"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect" />
</properties>
</persistence-unit>
</persistence>