Hibernate入门(二)基础部分

配置:

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();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值