自动建表:
<property name="hbm2ddl.auto">update</property>
问题:
之前没加:
- <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
成功:
控制台输出:
Hibernate: create table object (objectId integer not null auto_increment, objectName varchar(255), objectnum integer, primary key (objectId)) engine=InnoDB
Hibernate: insert into object (objectName, objectnum) values (?, ?)
代码:
package com.haibo.object;
public class object {
private int objectId;
public int getObjectId() {
return objectId;
}
public void setObjectId(int objectId) {
this.objectId = objectId;
}
public String getObjectName() {
return objectName;
}
public void setObjectName(String objectName) {
this.objectName = objectName;
}
public int getObjectnum() {
return objectnum;
}
public void setObjectnum(int objectnum) {
this.objectnum = objectnum;
}
private String objectName;
private int objectnum;
}
package com.haibo.object;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
public class objectTest {
Configuration cfg = null;
SessionFactory sf = null;
Session s = null;
Transaction ts = null;
@Test
public void add(){
object o=new object();
o.setObjectId(1);
o.setObjectName("apple");
o.setObjectnum(5);
try {
cfg = new Configuration().configure();
sf = cfg.buildSessionFactory();
s = sf.openSession();
ts = s.beginTransaction();
s.save(o);
ts.commit();
} catch (HibernateException e) {
if(ts != null)
{
ts.rollback();
}
e.printStackTrace();
}finally{
if(s != null){
s.close();
}
}
}
}
<?xml version="1.0"?>
<hibernate-mapping package="com.haibo.object">
<class name="object" table="object">
<id name="objectId" column="objectId">
<generator class="identity" /></id>
<property name="objectName" column="objectName"/>
<property name="objectnum" column="objectnum"/>
</class>
</hibernate-mapping>
<hibernate-configuration>
<session-factory>
<!-- 在控制台显示SQL语句 -->
<property name="show_sql">true</property>
<!-- 连接数据库的方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!-- 连接数据库的驱动名 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 连接数据库的URL -->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/user</property>
<!-- 连接数据库的用户名 密码-->
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<!-- 自动建表 -->
<property name="hbm2ddl.auto">update</property>
<!-- <mapping resource="com/Entity/User/User.hbm.xml"/>-->
<mapping resource="com/haibo/object/object.hbm.xml"/>
</session-factory>
</hibernate-configuration>
参考文章https://blog.csdn.net/u010066934/article/details/49078445点击打开链接
https://blog.csdn.net/lixuyuan/article/details/8057119点击打开链接