问候我的伙伴我正在使用JPA 2.0,到目前为止,我并没有从项目中的任何问题中得到任何错误,但是数据根本不会持久存入数据库,这是我的persistence.xml(只是pu文件,因为它现在看起来:
<persistence-unit name="auto-core-pu" transaction-type="RESOURCE_LOCAL">
<description>Auto Core Persistence Unit</description>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.auto.core.model.Cars</class>
<class>com.auto.core.model.Client</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/auto_core"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="123456"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
</properties>
</persistence-unit>
</persistence>
这是我的EntityManagerClient.class
package com.auto.core.persistence;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import com.auto.core.model.Cars;
public class EntityManagerClient {
public static void main(String[] args){
EntityManager em = Persistence.createEntityManagerFactory("auto-core-pu").createEntityManager();
EntityTransaction t = em.getTransaction();
t.begin();
Cars cr = new Cars();
cr.setBrand("Toyota");
cr.setModel("Camry");
cr.setEngine("V6");
cr.setDoors(5);
cr.setType("Jeepeta");
cr.setYear(123);
cr.setDescription("Auto usado del año 123 D.C.");
t.commit();
}
public static void getData(){
EntityManager em = Persistence.createEntityManagerFactory("auto-core-pu").createEntityManager();
EntityTransaction g = em.getTransaction();
g.begin();
Cars cr = em.createNamedQuery("Cars.FindbyId", Cars.class).setParameter("id", 1L).getSingleResult();
System.out.println(cr.getBrand());
}
}
并举例说明我如何在其他类中进行注释:
@Entity
@Table(schema="auto_core" , name="client")
public class Client {
@Id
@GeneratedValue
long id;
@Column(name="name")
String name;
@Column(name="lastname")
String lastname;
@Column(name="email")
String email;
@Column(name="address")
String address;
@Column(name="address2")
String address2;
@Column(name="zip")
String zip;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
同样,我没有收到任何类型的错误,只是因为我无法持久存储数据或查询我手动插入数据库的数据,这就是全部。
答案 0 :(得分:1)
这是因为您正在获取EntityManager,打开事务并创建对象,但您不会持久化它。你必须调用:
em.persist(cr);
前
t.commit();
在你persist
之前,它只是内存中的POJO。