JavaBean的主键类型只能是int类型,因为在映射关系中配置是自动增长的,String类型是不能自动增长的。如果是你设置了String类型,又使用了自动增长,那么就会报出下面的错误!
XML文件:
<hibernate-mapping package="zhongfucheng.domain">
<!--类名为User,表名也为User--> <class name="User" table="user"> <!--主键映射,属性名为id,列名也为id--> <id name="id" column="id">
<!--根据底层数据库主键自动增长-->
<generator class="native"/> </id>
<!--非主键映射,属性和列名一一对应-->
<property name="username" column="username"/>
<property name="cellphone" column="cellphone"/>
<property name="password" column="password"/>
<property name="registerTime" column="register_time" type="java.sql.Timestamp"></property>
<!-- 多对一,多个类型对应一个类别 -->
<many-to-one name="typesCategory" class="com.chen.bean.Categorys"
lazy="proxy">
<column name="types_category_id" not-null="true"></column>
</many-to-one>
<!-- 多对一,多个帖子对应一个用户 -->
<many-to-one name="topicsUser" class="com.yang.bean.Users" cascade="save-update" fetch="select" lazy="proxy">
<column name="topics_user_id" not-null="true"></column>
</many-to-one>
<!-- 一对多,一个帖子有多个评论 -->
<set name="topicComments" lazy="true">
<key column="comments_topic_id" foreign-key="id"></key>
<one-to-many class="com.yang.bean.Comments" />
</set>
</class>
</hibernate-mapping>
SessionFactory中取得Session的实例,SessionFactory在Hibernate中实际起到了一个缓冲区的作用,它缓冲了Hibernate自动生成的SQL语句和一些其它的映射数据,还缓冲了一些将来有可能重复利用的数据。如果一个项目有多个数据库,用多个SessionFactory。
private SessionFactory sessionFactory;get和set方法
Session session=sessionFactory.getCurrentSession();//hibernate中的session
Grades grade=(Grades) session.get(Grades.class, id);
用hibernate操作数据:
DaoImpl类中进行增删数据操作:
public boolean add(Users user, String x) {
Session session=this.sessionFactory.getCurrentSession();
user.setPassword(x);
System.out.print(x);
session.save(user);
return true;
}
public boolean findByName(String userName) {
// TODO Auto-generated method stub
String hql = "from Users u where u.username=?";
Session session =this.sessionFactory.getCurrentSession();
List<Users> listUser=null;
try{
Query q=session.createQuery(hql);
q.setString(0, userName);
listUser =q.list();
}catch(HibernateException e){
e.printStackTrace();
} finally {
// session.close();
}
if(listUser.size()>0){
return true;
}else
return false;
}
备注:session.delete(),session.find()
:
public boolean add(Users user, String x) {
Session session=this.sessionFactory.getCurrentSession();
user.setPassword(x);
System.out.print(x);
session.save(user);
return true;
}