hibernate连接Mysql数据库为什么可以更新,查找和删除但是就不能插入数据
hibernate连接Mysql数据库为什么可以更新,查找和删除但是就不能插入数据
其他描述:
数据库表:
guestbook
id int primary key
username varchar(20)
password varchar(20)
数据库guestbook的导出xml文件为:Guestbook.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<hibernate-mapping>
<class name="com.ssh.guestbook.Guestbook" table="guestbook" catalog="test">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="native" />
</id>
<property name="username" type="java.lang.String">
<column name="username" />
</property>
<property name="password" type="java.lang.String">
<column name="password" />
</property>
</class>
</hibernate-mapping>
对数据库的操作为:
Session session = HibernateSessionFactory.getSession();
Transaction t = session.beginTransaction();
List list = null;
Query q = null;
Guestbook gb = new Guestbook();
// 查询所有的记录
System.out.println("查询所有的记录");
q = session.createQuery("from Guestbook");
list = q.list();
System.out.println(list.size());
for (int i = 0; i <list.size(); i++) {
gb = (Guestbook) list.get(i);
System.out.println("id:" + gb.getId() + ",name:" + gb.getUsername()
+ ",password:" + gb.getPassword());
}
gb=null;
// 更新一条记录
System.out.println("更新一条记录");
gb = (Guestbook) session.get(Guestbook.class, new Integer(1));
if(gb!=null){
gb.setPassword("zwy");
t.begin();
session.saveOrUpdate(gb);
t.commit();
System.out.println("更新一条记录成功");
}
// 查询所有的记录
System.out.println("查询所有的记录");
q = session.createQuery("from Guestbook");
list = q.list();
for (int i = 0; i <list.size(); i++) {
gb = (Guestbook) list.get(i);
System.out.println("id:" + gb.getId() + ",name:" + gb.getUsername()
+ ",password:" + gb.getPassword());
}
//删除一条记录
System.out.println("删除一条记录");
gb=null;
gb=(Guestbook)session.get(Guestbook.class, new Integer(2));
if(gb!=null){
t.begin();
session.delete(gb);
t.commit();
}
// 查询所有的记录
System.out.println("查询所有的记录");
q = session.createQuery("from Guestbook ");
list = q.list();
for (int i = 0; i <list.size(); i++) {
gb = (Guestbook) list.get(i);
System.out.println("id:" + gb.getId() + ",name:" + gb.getUsername()
+ ",password:" + gb.getPassword());
}
session.close();
此操作的结果为:
查询所有的记录
Hibernate: select guestbook0_.id as id0_, guestbook0_.username as username0_, guestbook0_.password as password0_ from test.guestbook guestbook0_
2
id:1,name:zhou,password:zwy
id:2,name:sd,password:sd
更新一条记录
更新一条记录成功
查询所有的记录
Hibernate: select guestbook0_.id as id0_, guestbook0_.username as username0_, guestbook0_.password as password0_ from test.guestbook guestbook0_
id:1,name:zhou,password:zwy
id:2,name:sd,password:sd
删除一条记录