【问题标题】:Hibernate: Error Could not locate SessionFactory in JNDIHibernate:错误无法在 JNDI 中找到 SessionFactory
【发布时间】:2016-04-20 15:01:11
【问题描述】:

我是 Hibernate 的新手用户。我在 MySQL 中设计了一个数据库,并使用 HibernateTools 自动生成了类。 对于每个表,HibernateTools 都创建了 2 个类,一个代表表本身,另一个代表 Home 对象和持久化。例如,Users 表有 Users.java 和 UsersHome.java

用户.java

public class User implements java.io.Serializable {

private Integer idUsuario;
private String nomUsuario;
private String mailUsuario;
private String pass;
private Date ultConexion;
private Date fechaAlta;
private Date ultimoIngreso;
private Date ultimoGasto;
@SuppressWarnings("rawtypes")
private Set avisoses = new HashSet(0);
@SuppressWarnings("rawtypes")
private Set conceptoses = new HashSet(0);

public User() {
}

public User(String nomUsuario, String mailUsuario, String pass, Date ultConexion, Date fechaAlta) {
    this.nomUsuario = nomUsuario;
    this.mailUsuario = mailUsuario;
    this.pass = pass;
    this.ultConexion = ultConexion;
    this.fechaAlta = fechaAlta;
}

@SuppressWarnings("rawtypes")
public User(String nomUsuario, String mailUsuario, String pass, Date ultConexion, Date fechaAlta,
        Date ultimoIngreso, Date ultimoGasto, Set avisoses, Set conceptoses) {
    this.nomUsuario = nomUsuario;
    this.mailUsuario = mailUsuario;
    this.pass = pass;
    this.ultConexion = ultConexion;
    this.fechaAlta = fechaAlta;
    this.ultimoIngreso = ultimoIngreso;
    this.ultimoGasto = ultimoGasto;
    this.avisoses = avisoses;
    this.conceptoses = conceptoses;
}

public Integer getIdUsuario() {
    return this.idUsuario;
}

public void setIdUsuario(Integer idUsuario) {
    this.idUsuario = idUsuario;
}

public String getNomUsuario() {
    return this.nomUsuario;
}

public void setNomUsuario(String nomUsuario) {
    this.nomUsuario = nomUsuario;
}

public String getMailUsuario() {
    return this.mailUsuario;
}

public void setMailUsuario(String mailUsuario) {
    this.mailUsuario = mailUsuario;
}

public String getPass() {
    return this.pass;
}

public void setPass(String pass) {
    this.pass = pass;
}

public Date getUltConexion() {
    return this.ultConexion;
}

public void setUltConexion(Date ultConexion) {
    this.ultConexion = ultConexion;
}

public Date getFechaAlta() {
    return this.fechaAlta;
}

public void setFechaAlta(Date fechaAlta) {
    this.fechaAlta = fechaAlta;
}

public Date getUltimoIngreso() {
    return this.ultimoIngreso;
}

public void setUltimoIngreso(Date ultimoIngreso) {
    this.ultimoIngreso = ultimoIngreso;
}

public Date getUltimoGasto() {
    return this.ultimoGasto;
}

public void setUltimoGasto(Date ultimoGasto) {
    this.ultimoGasto = ultimoGasto;
}

@SuppressWarnings("rawtypes")
public Set getAvisoses() {
    return this.avisoses;
}

@SuppressWarnings("rawtypes")
public void setAvisoses(Set avisoses) {
    this.avisoses = avisoses;
}

@SuppressWarnings("rawtypes")
public Set getConceptoses() {
    return this.conceptoses;
}

@SuppressWarnings("rawtypes")
public void setConceptoses(Set conceptoses) {
    this.conceptoses = conceptoses;
}

UserHome.java

public class UserHome {

private static final Log log = LogFactory.getLog(UserHome.class);

private final SessionFactory sessionFactory = getSessionFactory();

protected SessionFactory getSessionFactory() {
    try {
        return (SessionFactory) new InitialContext().lookup("SessionFactory");
    } catch (Exception e) {
        log.error("Could not locate SessionFactory in JNDI", e);
        throw new IllegalStateException("Could not locate SessionFactory in JNDI");
    }
}

public void persist(User transientInstance) {
    log.debug("persisting User instance");
    try {
        sessionFactory.getCurrentSession().persist(transientInstance);
        log.debug("persist successful");
    } catch (RuntimeException re) {
        log.error("persist failed", re);
        throw re;
    }
}

public void attachDirty(User instance) {
    log.debug("attaching dirty User instance");
    try {
        sessionFactory.getCurrentSession().saveOrUpdate(instance);
        log.debug("attach successful");
    } catch (RuntimeException re) {
        log.error("attach failed", re);
        throw re;
    }
}

public void attachClean(User instance) {
    log.debug("attaching clean User instance");
    try {
        sessionFactory.getCurrentSession().lock(instance, LockMode.NONE);
        log.debug("attach successful");
    } catch (RuntimeException re) {
        log.error("attach failed", re);
        throw re;
    }
}

public void delete(User persistentInstance) {
    log.debug("deleting User instance");
    try {
        sessionFactory.getCurrentSession().delete(persistentInstance);
        log.debug("delete successful");
    } catch (RuntimeException re) {
        log.error("delete failed", re);
        throw re;
    }
}

public User merge(User detachedInstance) {
    log.debug("merging User instance");
    try {
        User result = (User) sessionFactory.getCurrentSession().merge(detachedInstance);
        log.debug("merge successful");
        return result;
    } catch (RuntimeException re) {
        log.error("merge failed", re);
        throw re;
    }
}

public User findById(java.lang.Integer id) {
    log.debug("getting User instance with id: " + id);
    try {
        User instance = (User) sessionFactory.getCurrentSession().get("Usuario", id);
        if (instance == null) {
            log.debug("get successful, no instance found");
        } else {
            log.debug("get successful, instance found");
        }
        return instance;
    } catch (RuntimeException re) {
        log.error("get failed", re);
        throw re;
    }
}

@SuppressWarnings("rawtypes")
public List findByExample(User instance) {
    log.debug("finding User instance by example");
    try {
        List results = sessionFactory.getCurrentSession().createCriteria("User").add(Example.create(instance))
                .list();
        log.debug("find by example successful, result size: " + results.size());
        return results;
    } catch (RuntimeException re) {
        log.error("find by example failed", re);
        throw re;
    }
}

}

当我尝试这样做以查看一切是否按预期进行时,我得到“无法在 JNDI 中找到 SessionFactory”

UserHome uh = new UserHome();
User u = new User("nom", "Mail1@mail.com", "chsss", new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis()));
uh.persist(u);

我做错了什么?

编辑:异常的完整堆栈跟踪

abr 21, 2016 8:47:09 AM hibernate.UsuarioHome getSessionFactory
SEVERE: Could not locate SessionFactory in JNDI
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.lookup(Unknown Source)
at hibernate.UserHome.getSessionFactory(UserHome.java:27)
at hibernate.UserHome.<init>(UserHome.java:23)
at bbdd.FirstHibernate.main(FirstHibernate.java:11)

Exception in thread "main" java.lang.IllegalStateException: Could not locate SessionFactory in JNDI
at hibernate.UserHome.getSessionFactory(UserHome.java:30)
at hibernate.UserHome.<init>(UserHome.java:23)
at bbdd.FirstHibernate.main(FirstHibernate.java:11)

【问题讨论】:

    标签: java mysql hibernate


    【解决方案1】:

    您有初始上下文吗?仅当您在应用程序服务器上运行代码时才会存在初始上下文。如果您在应用程序服务器上运行此代码,请添加您的配置文件,以便我可以验证它是否配置正确。如果没有应用程序服务器并且代码是从 POJO 运行的,则需要以不同的方式获取会话工厂。看看你的类,我认为你是在 POJO 中运行的。

    如果您可以粘贴异常或堆栈跟踪,也会有所帮助。更容易猜出问题所在。

    【讨论】:

    • 没有应用服务器,是的,代码是从 POJO 运行的。我将更新添加异常的初始帖子,但我不知道如何获取会话工厂,当我运行 UserHome uh = new UserHome(); 时应该这样做对吗?
    • 对不起,我出去了几天,所以延迟是响应。在 Pojo 中,您没有 JNDI 或初始上下文。您需要使用配置对象来获取会话工厂。 SessionFactory ss = 新配置()。 configure("cfg.xml 的路径").buildSessionFactory();
    猜你喜欢
    • 2013-04-29
    • 2010-12-09
    • 2012-08-25
    • 2014-06-10
    • 2011-01-29
    • 1970-01-01
    • 2016-05-19
    • 2010-10-14
    • 2018-03-22
    相关资源
    最近更新 更多