1:导入Hibernate库
2:添加配置文件 – hibernate.cfg.xml
<hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hellohibernate?useSSL=false</property> <property name="hibernate.connection.username"></property>//用户名 <property name="hibernate.connection.password"></property>//密码 <property name="show_sql">true</property> <mapping resource="cn/hrbust/pojo/User.hbm.xml"/> </session-factory> </hibernate-configuration>
3:添加实体类和映射文件
import java.util.Date;
public class User {
private int id;
private String name;
private String gender;
int age;
Date birthday;
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 getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
设计数据库:
导入User.hbm.xml
测试:创建manageUser.java
import java.sql.Date;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import cn.hrbust.pojo.User;
public class manageUser {
public static void main(String[] args) {
// TODO Auto-generated method stub
Configuration cfg = null;
SessionFactory sf = null;
Session session = null;
Transaction ts = null;
User u = new User();
u.setName(“ztr”);//添加名字
u.setGender(“男”);//添加性别
u.setAge(21);//添加年龄
u.setBirthday(Date.valueOf(“2000-4-1”));//添加生日
try {
cfg = new Configuration().configure();
sf = cfg.buildSessionFactory();
session = sf.openSession();
ts = session.beginTransaction();
session.save(u);
ts.commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if(ts != null) {
ts.rollback();
}
} finally {
session.close();
sf.close();
}
}
}
数据库中添加成功: