LocalSessionFactoryBean

LocalSessionFactoryBean

我正在关注异常


  org.hibernate.MappingException:未知实体:com.sample.Student


我在Stackoverflow上看到了很多相同问题的答案,但是所有这些人都建议使用javax.persistence中的@Entity批注而不是休眠,在我的情况下,我仅从javax.persistence中使用它,但仍收到此异常。

我的POJO课

package com.sample;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table
public class Student {

    @Id
    int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    String firstName;
    String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}


和我的经理班

   package com.sample;

import java.util.Properties;

import org.hibernate.SessionFactory;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;

public class ORMManager {

    /**
     * @param args
     */
    public static void main(String[] args) {
    DriverManagerDataSource ds = new DriverManagerDataSource();
    ds.setUrl("jdbc:oracle:thin:@localhost:1521:XE");
    ds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
    ds.setUsername("system");
    ds.setPassword("tiger");

    LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
    lsfb.setDataSource(ds);
    HibernateTemplate template = new HibernateTemplate();
    Properties prop = new Properties();
    prop.put("hibernate.dialect", "org.hibernate.dialect.OracleDialect");
    prop.put("hibernate.show_sql", "true");
    prop.put("hbm2ddl.auto", "create");

    lsfb.setHibernateProperties(prop);
    try {
        lsfb.afterPropertiesSet();
    } catch (Exception e) {

        e.printStackTrace();
    }
    template.setSessionFactory((SessionFactory)lsfb.getObject());
    template.afterPropertiesSet();

    Student s = new Student();
    s.setFirstName("pallavi");
    s.setLastName("sing");
    template.save(s);
    System.out.println("done");


    }

}


请帮助我解决此问题

最佳答案

您正在尝试混合两件事


  注解





  LocalSessionFactoryBean


使用LocalSessionFactoryBean的子类


  AnnotationSessionFactoryBean


取代这个


  LocalSessionFactoryBean lsfb =新的LocalSessionFactoryBean();




  AnnotationSessionFactoryBean lsfb = new AnnotationSessionFactoryBean();
  Class [] annotatedClasses =  {Student.class};
  lsfb.setAnnotatedClasses(annotatedClasses);


要么

  AnnotationSessionFactoryBean lsfb = new AnnotationSessionFactoryBean();
  annotationSessionFactoryBean.setPackagesToScan(new String[]{"com.sample"});


看到这个answer

10-04 20:11