<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<!--类和表之间的关联-->
<class name="hibernate.ch01.UserInfo" table="login">
<!--类对象的主键和表的主键的关联-->
<id name="id" type="integer">
<column name="id" />
<!--指明主键的自增长类型-->
<generator class="identity"/>
</id>
<!--以下为普通字段的关联-->
<property name="userName" type="string">
<column name="name" length="100" />
</property>
<property name="password" type="string">
<column name="password" length="100" />
</property>
</class>
</hibernate-mapping>
import hibernate.ch01.UserInfo;
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class HibernateTest {
public static void main(String[] args) {
Configuration config = new Configuration().configure();
SessionFactory sessions= config.buildSessionFactory();
Session session = sessions.openSession();
Transaction tx = null;
try {
//开始事务
tx = session.beginTransaction();
// //给对象设定值
UserInfo u = new UserInfo();
u.setId(5);
u.setUserName("liu");
u.setPassword("123");
System.out.println("开始插入数据到数据库……");
// //保存数据到数据库
session.save(u);
//从持久化类UserInfo中读取数据
String hql="from UserInfo userInfo where userInfo.userName like ?";
Query query=session.createQuery(hql);
//模糊查询默认不区分大小写
query.setParameter(0,"liu");
List list=query.list();
Iterator it=list.iterator();
while(it.hasNext()){
UserInfo userInfo=(UserInfo)it.next();
System.out.println(userInfo.getUserName());
}
//结束事务
tx.commit();
tx = null;
} catch (HibernateException e) {
e.printStackTrace();
if (tx != null) {
tx.rollback();
}
} finally {
session.close();
}
}
}
因为Identity策略指的是由数据库自动生成,所以在程序中通过setId()方法去设定其主键值是没有任何效果的.而且每保存一次都会增加一条新的记录.每增加一条记录,主键值每次增加1.