hibernate
?
Specify additional Hibernate properties.
<property name="hibernate.show_sql">true</property>
<property name="hibernate.transaction.factory_class">
org.hibernate.transaction.JDBCTransactionFactory
</property>
HibernateUtil的currentSession方法产生sessionFactory和session(Static与下面有点不一样)
SessionFactory sessionFactory=new Configuration().configure()
.buildSessionFactory();
Session session=sessionFactory.openSession();
使用HiberanteUtil的currentSession方法。
Session dbSession = HibernateUtil.currentSession();
也可使用Session session=HiberanateSessionFactory.getSession();
HibernateUtil.beginTransaction();
Query query = dbSession.createQuery(" from Bookinfo as b where b.id=:id")
.setInteger("id", id)
.setMaxResults(1);
List result = query.list();
HibernateUtil.commitTransaction();
session的方法 增删改选
session.saveOrUpdate(transistentDB);
session.delete(transistentDB);
session.update(transistentDB);
session.createQuery(sql).list();
事务
session.beginTransaction();
transaction.commit();
Query方法
String hqlStr = " from Userinfo as u where u.username=:username and u.pwd=:pwd";
Query query = dbSession.createQuery(hqlStr);
query.setString("username", form.getUserName());
query.setString("pwd", form.getPassword());
删除,添加成功,可数据库不显示
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
// Transaction tx = session.beginTransaction();
User user = new User();
user.setUsername("ericaj");
user.setPassword("mypass");
session.save(user);
// tx.commit();
session.close();
面已经显示成功了,可是数据库表里却没有执行删除操作。
有时候加上transcation.commit()就好了。
spring中不是这样了
UserDAO dao= new UserDAO();
要
BeanFactory factory=new ClassPathXmlApplicationContext("applicationContext.xml");
UserDAO dao= (UserDAO)factory.getBean("userDAO");
classpath:hibernate.cfg.xml
error creating bean with name 'hibernateTemplate' defined in class path resource
[applicationContext.xml]: Instantiation of bean failed; nested exception is
java.lang.IllegalStateException: No bean class specified on bean definitio
把
<bean id="hibernateTemplate"
name="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
改为:
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>