将Hibernate(3.2.5)与PostgreSQL(8.2)一起使用时,对象不会被持久存在

时间:2011-12-02 03:32:35

标签: java hibernate postgresql

我正在使用PostgreSQL(8.2)和Hibernate(3.2.5)。尽管在我尝试在后端运行我的代码段时有适当的注释,但是不会生成主键,因此它最终没有在表中插入记录。

我正在尝试在课堂(一面)和学生(多面)之间建立一对多的映射。请在下面找到我的代码:

课堂课程

@Entity
public class Classroom implements Serializable {  
    private static final long serialVersionUID = 1L;  

    @Id  
    @GeneratedValue(strategy = GenerationType.AUTO)  
    @Column(name="room_id")  
    private Long id;  

    @Column(name="Standard")  
    private String std;  

    @OneToMany(cascade=CascadeType.ALL)  
    @JoinColumn(name="room_id")  
    private Set<Student> students = new HashSet<Student>();  

   // with setters and getters
}

学生班级

@Entity  
public class Student implements Serializable {  
    private static final long serialVersionUID = 1L; 

    @Id  
    @GeneratedValue(strategy = GenerationType.AUTO)  
    @Column(name="roll_no")  
    private Long id;    

    @Column(name="name")  
    private String name; 

   // with setters and getters
}

主要

public class Main {

    public static void main(String arr[]){
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("OneTomanyMyDbPU");
        EntityManager em = emf.createEntityManager();

        Set<Student> students = new HashSet<Student>();

        Classroom c = new Classroom();

        Student s1 = new Student();
        Student s2 = new Student();

        s1.setName("abc");
        s2.setName("xyz");

        students.add(s1);
        students.add(s2);

        c.setStd("X");
        c.setStudents(students);

        try {
            EntityTransaction tr = em.getTransaction();

            System.out.println("Classroom b4 persisting...:"+c.getStd());
            em.persist(c);

            tr.commit();
        } catch(Exception e){
        }
    }
}

persistence.xml

<persistence-unit name="OneTomanyMyDbPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class> model.Classroom</class>
    <class> model.Student</class>
    <properties>
        <property name="hibernate.connection.username" value="postgres"/>
        <property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
        <property name="hibernate.connection.password" value="abc123"/>
        <property name="hibernate.connection.url" value="jdbc:postgresql://localhost/mydb"/>
        <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
        <property name="hibernate.hbm2ddl.auto" value="update"/>
    </properties>
</persistence-unit>

可能是什么原因?如何坚持下去?

1 个答案:

答案 0 :(得分:1)

您的hbm文件说ddl要更新,所以您永远不知道是否每次都在创建表,所以不要这样:

catch(Exception e){

}
你能放这个:

catch(Exception e){
   e.printStackTrace();
}

并重新运行