hibernate联合主键

<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<hibernate-mapping package="classweb.model.po">
<class
   name="Users"
   table="USERS"
>
   <meta attribute="sync-DAO">false</meta>
   <composite-id name="id" class="UsersPK">
    <key-property
     name="name"
     column="NAME"
     type="string"
    />
    <key-property
     name="tel"
     column="TEL"
     type="string"
    />
   </composite-id>

   <property
    name="age"
    column="AGE"
    type="string"
    not-null="false"
   />
 
</class>
</hibernate-mapping>

以下代码生成一个Users对象,并保存.

    Session s = HibernateUtil.currentSession();
    Transaction t = s.beginTransaction();
    UsersPK usersPK = new UsersPK();
    usersPK.setName(1);
    usersPK.setTel(4);
    Users user = new Users();
    user.setAge("19");
    user.setId(usersPK );
    s.save(user);
    t.commit();
    HibernateUtil.closeSession();
    System.out.println("insert success!");

更新.

    Session s = HibernateUtil.currentSession();
    Transaction t = s.beginTransaction();
    UsersPK usersPK = new UsersPK();
    usersPK.setDbid(1);
    usersPK.setRowUID(4);
    Users user = (Users)s.load(Users.class, usersPK);

    user.setAge("20");
    s.update(user);
    t.commit();
    HibernateUtil.closeSession();
    System.out.println("update success!");

删除.

Session s = HibernateUtil.currentSession();
    Transaction t = s.beginTransaction();
    UsersPK usersPK = new UsersPK();
    usersPK.setDbid(1);
    usersPK.setRowUID(4);
    Users user = (Users)s.load(Users.class, usersPK);

    s.delete(user);
    t.commit();
    HibernateUtil.closeSession();
    System.out.println("delete success!");

最后讲select

如果对复合主键中的一个主键进行查询,必须

    Session s = HibernateUtil.currentSession();
    Criteria c = s.createCriteria(Users.class);
    c.add(Restrictions.eq("id.name", "levi"));
    List list = c.list();
    Iterator iter = list.iterator();
    while (iter.hasNext()) {
      Users item = (Users) iter.next();
      System.out.println("name:" + item.getId().getName());
      System.out.println("tel;" + item.getId().getTel());
      System.out.println("age:" + item.getAge());
    }
    HibernateUtil.closeSession();
    System.out.println("select success!");

 

你可能感兴趣的:(Hibernate)