开发者

JPA do not insert in database, why?

开发者 https://www.devze.com 2023-04-02 14:24 出处:网络
i\'m new with JPA, i\'m using in a JSF 2 Project with Glassfish 3 and Eclipse Java EE Web Developers.

i'm new with JPA, i'm using in a JSF 2 Project with Glassfish 3 and Eclipse Java EE Web Developers. These are my settings and the way that I'm trying to persist in my database:

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>

My entity:

@开发者_JS百科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    


}

And how i'm calling my EntityManager and try to persist the object:

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);

}

But when i execute nothing happens in my database, JPA do not persist the object in my table, what i'm doing wrong ? Any idea ?


You lack transaction handling, e.g.

entityManager.getTransaction().begin();
entityManager.persist(area);
entityManager.getTransaction().commit();

I recommend you read up on JPA and JSF integration, there might be some utility/filter/JSF support that takes care of this for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消