配置:
File file = new File("src\\hibernate\\MyConfig.cfg.xml");
configuration = new Configuration().configure(file);
configuration.addClass(UserInfo.class);
configuration.addFile("src\\hibernate\\bean\\UserInfo.hbm.xml");
读取
session.get(UserInfo.class, new Integer(1));
session.load(UserInfo.class, new Integer(1));//前提是存在指定的数据
删除
String hql = "delete UserInfo where id = 1";
Query query = session.createQuery(hql);
query.executeUpdate();
session.delete("from UserInfo where id = 1");
查询
String hql = "from UserInfo a where a.userName like ?";
Query query = session.createQuery(hql);
query.setParameter(0, "ok");
List list = query.list();
Iterator iterator = list.iterator();
while(iterator.hasNext())
{
((UserInfo)iterator.next()).getUserName();
}
改装后的SessionFactory
public class HibernateSessionFactory
{
private static String CONFIG_FILE_LOCATION = "hibernate.cfg.xml";
private static final ThreadLocal threadLocal = new ThreadLocal();
private static final Configuration configuration = new Configuration();
private static SessionFactory sessionFactory = null;
public static Session currentSession() throws HibernateException
{
Session session = (Session)threadLocal.get();
if(session == null || !session.isOpen())
{
if(sessionFactory == null)
{
configuration.configure(CONFIG_FILE_LOCATION);
sessionFactory = configuration.buildSessionFactory();
}
session = (sessionFactory == null) ? null : sessionFactory.openSession();
}
return session;
}
public static void closeSession() throws HibernateException
{
Session session = (Session)threadLocal.get();
threadLocal.set(null);
if(session != null)
session.close();
}
}
复合主键:
<composite-id>
<key-property name="" type="integer" column=""></key-property>
<key-property name="" type="integer" column=""></key-property>
</composite-id>
分页
query.setFirstResult() setMaxResults();
一般先查处数据库中有多少记录,然后对应页从哪条记录开始,
在映射文件中配置HQL
<query name="searchUser">
<![CDATA[
from UserInfo s where s.userName = ?
]]>
</query>
定义在class之外
Query query = session.getNamedQuery("searchUser");
query.setParameter(0, "1");
query.list();