解决hibernate只能插入一条数据的问题

时间:2021-11-18 12:53:32

hibernate初学,根据视频教程写好代码后,发现无论执行多少次main函数,数据库中只有一条数据,尝试多次,后来终于发现问题。。。

使用的工具是:MYSQL 5.7.13   eclipse 4.5.2  hibernate 4.0.5

第一步:

在mysql中新建一个数据库 名为DEMO01,然后再创建一个test表:

USE DEMO01;
CREATE TABLE test(
TEST_ID int auto_increment,
name varchar(20),
TEST_DATE date,
primary key(TEST_ID)
)engine=InnoDB default charset=utf8 auto_increment=1;

第二步:

新建一个Java project,添加持久化类

package com.hibernate.demo;
/*
*持久化类test
*/
import java.util.Date; public class test {
private int id;
private String name;
private Date time; public test(){} public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
} @Override
public String toString() {
return "test [id=" + id + ", name=" + name + ", time=" + time + "]";
} }

第三步:

创建Hibernate的映射文件,其中property中的name对应持久化类中的属性,column中的name对应数据库中的字段名

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-8-13 17:46:08 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="com.hibernate.demo.test" table="TEST">
<id name="id" type="int">
<column name="TEST_ID" />
<generator class="assigned" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" />
</property>
<property name="time" type="java.util.Date">
<column name="TEST_DATE" />
</property>
</class>
</hibernate-mapping>

第四步:

创建Hibernate配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql:///demo01?useUnicode=true&amp;characterEncoding=UTF-8</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property> <mapping resource="com/hibernate/demo/test.hbm.xml"/>
</session-factory>
</hibernate-configuration>

Hibernate配置文件内容都是以键值对的形式进行配置:

connection.driver_class指连接数据库的驱动,对不同的关系数据库,驱动不同,需要根据实际情况修改;

connection.url指对应的数据库的url;

dialect指对应的数据库方言;

show_sql指程序运行时是否在控制台输出SQL语句,true 输出,false 不输出。默认false,在调试程序时一般设为true,发布程序前改为false,因为输出SQL语句会影响程序的运行速度;

format_sql指程序运行时,是否在SQL语句中输出便于调试的注释信息。true 输出,false 不输出,默认false。该属性只有当show_sql为true时才有效。

hbm2dd.auto指对数据库的数据进行的操作类型:

create:每次加载hibernate,重新创建数据库表结构

create-drop:加载hibernate时创建,退出时删除表结构

update:加载hibernate自动更新数据库结构

validate:加载hibernate时,验证创建数据库表结构

嗯。。。。我的问题就出现在这里。。。一开始是写的create,后来改为update就没问题了。。。一旦发现数据库表丢失,首先看这里设置的值。。。

第五步:

创建会话工厂以及测试实例,增删查改都有,不过可能方案不全(按道理应该分开来写,我这里写一起了,偷了个懒~)

package com.hibernate.demo;

import java.util.Date;
import java.util.List; import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration; public class testManage {
private static final SessionFactory sessionFactory=buildSessionFactory(); private static SessionFactory buildSessionFactory() {
//创建配置对象
Configuration cfg = new Configuration().configure();
//创建服务注册对象
StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties());
StandardServiceRegistry sr = srb.build();
//创建工厂会话对象
return cfg.buildSessionFactory(sr);
} public static void main(String[] args) { Session session=sessionFactory.openSession();
session.beginTransaction(); //新增
test theTest=new test();
theTest.setName("mist332!");
theTest.setTime(new Date());
session.save(theTest); //更新
/*test uTest=new test();
uTest.setId(1);//id不能少,Hibernate是根据ID来查询数据进行更新的
uTest.setName("全宇宙我最帅啦~~~");
session.update(uTest);*/ //删除
/*test dTest=new test();
dTest.setId(1);//hibernate先进行查询,再删除
test dTest1=(test)session.get(test.class, 1);
session.delete(dTest1);
*/ //查询 //HQL查询,是Hibernate主推的查询方式,和SQL比较像,但是form后面是Java类名,不是数据库表名,
//如果查询全字段 select * 可以省略不写
/*Query query=session.createQuery("from test");
List<test> list=query.list();
for(test t:list){
System.out.println(t.toString());
}*/ //当不是查询全字段,或者是从两张表中联合查询数据时,返回的是一个数组:
/*Query query=session.createQuery(" select s.name,t.name from Student s ,test t ");
List<Object[]> list=query.list();//这里的每一行都是一个一维数组
for(int i=0;i<list.size();i++){
Object []o=(Object[]) list.get(i);//转型为数组
String name1=(String) o[0];//与select中顺序的类型相对应,可以是类
String name2=(String) o[1];
System.out.println("Student中的name:"+name1+"test中的name:"+name2);
System.out.println("查出来了~~~~~~~~");
}*/ session.getTransaction().commit();
session.close();
sessionFactory.close();;
} }

如果我们把设置为create,那么执行的SQL就会是:

INFO: HHH000227: Running hbm2ddl schema export
Hibernate:
drop table if exists TEST
Hibernate:
create table TEST (
TEST_ID integer not null,
NAME varchar(255),
TEST_DATE datetime,
primary key (TEST_ID)
)
八月 13, 2016 6:20:03 下午 org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate:
insert
into
TEST
(NAME, TEST_DATE, TEST_ID)
values
(?, ?, ?)
八月 13, 2016 6:20:04 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:mysql:///demo01?useUnicode=true&characterEncoding=UTF-8]
插入成功!

如果设置为update:

八月 13, 2016 6:44:24 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Hibernate:
insert
into
TEST
(NAME, TEST_DATE)
values
(?, ?)
八月 13, 2016 6:44:24 下午 org.hibernate.engine.jdbc.spi.SqlExceptionHelper$StandardWarningHandler logWarning
WARN: SQL Warning Code: 1292, SQLState: 22007
八月 13, 2016 6:44:24 下午 org.hibernate.engine.jdbc.spi.SqlExceptionHelper$StandardWarningHandler logWarning
WARN: Incorrect date value: '2016-08-13 18:44:24.789' for column 'TEST_DATE' at row 1
八月 13, 2016 6:44:24 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:mysql:///demo02?useUnicode=true&characterEncoding=UTF-8]
插入成功!

从打印的SQL语句中很容易就可以看出区别啦~