hibernate.cfg.xml
<?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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///hibernate_day01</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 映射配置文件,需要引入映射的配置文件 -->
<mapping resource="domain/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
User.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="domain.User" table="user">
<id name="id" column="id">
<generator class="native"/>
</id>
<property name="name" column="name"/>
<property name="sex" column="sex"/>
<property name="age" column="age"/>
<property name="height" column="height"/>
<property name="hobby" column="hobby"/>
</class>
</hibernate-mapping>
User.java
package domain;
public class User {
private String name;
private String sex;
private int age;
private int height;
private String hobby;
private int id;
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 String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
@Override
public String toString() {
return "User [name=" + name + ", sex=" + sex + ", age=" + age + ", height=" + height + ", hobby=" + hobby + "]";
}
}
Demo1.java
package homework;
import org.hibernate.Session;
import org.hibernate.Transaction;
import domain.User;
import utils.HibernateUtils;
public class Demo1 {
public static void main(String[] args) {
Session session = HibernateUtils.getSession();
Transaction ts = session.beginTransaction();
User user = new User();
user.setName("宋长乾");
user.setSex("男");
user.setAge(21);
user.setHeight(170);
user.setHobby("写代码");
session.save(user);
ts.commit();
session.close();
}
}
在最后传输数据的时候,数据提交不到数据库,问题是我没把表的id属性设置为自增的,所以运用hibernate框架提交数据的时候会报错。