我是JPA的新手,我正在使用Glassfish 3和Eclipse Java EE Web开发人员的JSF 2项目。 这些是我的设置以及我尝试在数据库中保留的方式:
的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="SuaParte" transaction-type="RESOURCE_LOCAL">
<class>com.suaparte.pojo.Area</class>
//other entities
<properties>
<property name="eclipselink.jdbc.batch-writing" value="JDBC"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://<hostname>:3306/sua_parte"/>
<property name="javax.persistence.jdbc.user" value=<username>/>
<property name="javax.persistence.jdbc.password" value=<password>/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
</properties>
</persistence-unit>
</persistence>
我的实体:
@Entity
@Table(name="area")
public class Area implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(unique=true, nullable=false)
private byte id;
@Column(nullable=false, length=45)
private String area;
//bi-directional many-to-one association to Company
@OneToMany(mappedBy="areaBean")
private List<Company> companies;
//getters and setters
}
以及我如何调用我的EntityManager并尝试保留该对象:
public static void main(String[] args) {
// TODO Auto-generated method stub
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("SuaParte");
EntityManager entityManager = entityManagerFactory.createEntityManager();
Area area = new Area();
area.setArea("test");
entityManager.persist(area);
}
但是当我在我的数据库中没有执行任何操作时,JPA不会将对象保留在我的表中,我做错了什么? 有什么想法吗?
答案 0 :(得分:3)
你缺少transaction handling,例如
entityManager.getTransaction().begin();
entityManager.persist(area);
entityManager.getTransaction().commit();
我建议您阅读JPA和JSF集成,可能会有一些实用程序/过滤器/ JSF支持为您解决此问题。