如何正确配置Hibernate
用于执行任务的DataFetcher.java如何正确配置Hibernate,hibernate,Hibernate,用于执行任务的DataFetcher.java public class HibernateSession { private static final SessionFactory sessionFactory; static { try { sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); } catc
public class HibernateSession {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch ( Throwable ex ) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
}
如何正确配置Hibernate?我做的每一笔交易都有almogs的问题!
在本例中,我得到“信息:非法尝试将集合与两个打开的会话关联”。当我
更改会话时,保存(m);到session.merge(m)代码>只要我在同一页上,它就会工作。当我更改页面,然后返回页面时,会出现很多异常 不要将会话对象存储在数据获取程序中。那不是个好主意。每个会话都绑定到一个事务,该事务绑定到它的线程。我不确定这段代码是否在容器中运行,但如果是这样,hibernate将尝试使用范围内事务管理器,您的代码将因此而混淆。将您的代码更改为以下内容,然后查看是否有任何更改
公共类数据获取程序{
public class DataFetcher {
Session session;
public DataFetcher()
{
session = HibernateSession.getSessionFactory().getCurrentSession();
}
public void Save(Marki m)
{
org.hibernate.Transaction tx = session.beginTransaction();
session.save(m);
session.getTransaction().commit();
}
}
ManagedBean(name="dodaj")
@ViewScoped
public class DodajOferte implements Serializable {
private Marki marka;
public DodajOferte()
{
marka = new Marki();
}
public String Dodaj()
{
DataFetcher f = new DataFetcher();
try {
f.Save(marka);
} catch ( HibernateException ex ) {
System.out.println(ex.getMessage().toString());
FacesMessage message = new FacesMessage("err");
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, message);
return null;
}
return null;
}
public Marki getMarka()
{
return marka;
}
public void setMarka(Marki marka)
{
this.marka = marka;
}
}
看起来合并不再有效。
public class DataFetcher {
Session session;
public DataFetcher()
{
session = HibernateSession.getSessionFactory().getCurrentSession();
}
public void Save(Marki m)
{
org.hibernate.Transaction tx = session.beginTransaction();
session.save(m);
session.getTransaction().commit();
}
}
ManagedBean(name="dodaj")
@ViewScoped
public class DodajOferte implements Serializable {
private Marki marka;
public DodajOferte()
{
marka = new Marki();
}
public String Dodaj()
{
DataFetcher f = new DataFetcher();
try {
f.Save(marka);
} catch ( HibernateException ex ) {
System.out.println(ex.getMessage().toString());
FacesMessage message = new FacesMessage("err");
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, message);
return null;
}
return null;
}
public Marki getMarka()
{
return marka;
}
public void setMarka(Marki marka)
{
this.marka = marka;
}
}
public void Save(Marki m)
{
Session session = HibernateSession.getSessionFactory().getCurrentSession();
org.hibernate.Transaction tx = session.beginTransaction();
session.save(m);
session.getTransaction().commit();
}
}