Я новичок в Hibernate. Я разработал базу данных в MySQL и автоматически генерировал классы с использованием HibernateTools. Для каждой таблицы HibernateTools создал 2 класса, один из которых представляет собой таблицу, а другой - объект Home с сохранением. Например таблица пользователей имеет Users.java и UsersHome.javaСпящий режим: ошибка Не удалось найти SessionFactory в JNDI
User.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;
}
}
}
Когда я делаю это как проба чтобы убедиться, что все идет так, как предполагалось, я получаю «Не удалось найти SessionFactory в JNDI»
UserHome uh = new UserHome();
User u = new User("nom", "[email protected]", "chsss", new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis()));
uh.persist(u);
Что я делаю неправильно?
Edit: Полный StackTrace за исключением
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)
Нет сервера приложений, и да, код запускается с POJO. Я буду обновлять начальную запись, добавляя исключение, но я не знаю, как получить фабрику сеансов, она должна делать это, когда я запускаю UserHome uh = new UserHome(); правильно? –
Жаль, что я отсутствовал на несколько дней, поэтому отсрочка - это ответ. В Pojo у вас нет JNDI или inital контекста. Чтобы получить фабрику сеансов, вам нужно использовать объект конфигурации. SessionFactory ss = new Configuration(). configure («путь к cfg.xml»). buildSessionFactory(); –