hibernate案例数据库增加数据

原项目下载传送门:http://download.csdn.net/download/six_666666/9988353

项目架构

hibernate案例数据库增加数据_第1张图片

Person.java
package yw;

public class Person {
private Integer id;
private String name;
private int password;
public Person(Integer id,String name, int password) {
super();
this.id=id;
this.name = name;
this.password = password;
}
public int getPassword() {
return password;
}
public void setPassword(int password) {
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Test.java
package yw;
import java.sql.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import yw.Person;

public class Test {
static Test mt = new Test();
public static void main(String[] args) {
Configuration config = new Configuration().configure();
// 原来configure()方法默认会在classpath下面寻找hibernate.cfg.xml文件,如果没有找到该文件,系统会打印 如下信息并抛出HibernateException异常。
SessionFactory sessionFactory = config.buildSessionFactory();
//此方法已过时4.0中已不再用被 ServiceRegistry替代
Session session = sessionFactory.openSession();
//打开一个新的session对象
Transaction tx = session.beginTransaction();
//开启事务
session.save(mt.add());
//保存新创建的对象
tx.commit();
//提交
//session.close();
sessionFactory.close();//一定 不 要 关闭.这里只是写出来做例子
/*注意:sessionFactory一定不要关闭.原因是:
它线程安全,所以一个程序只需要获取一次.如果每次都关闭, 重新获取执行效率降低!!!
*/
}
private Person add() {
Person p = new Person(1,"张三", 123);
return p;
}
}

Person.hbm.xml
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

hibernate.cfg.xml
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
com.mysql.jdbc.Driver
jdbc:mysql:///hb?useUnicode=true&characterEncoding=UTF8
root
root
org.hibernate.dialect.MySQL5Dialect
true
true
update

测试结果( 第一次的时候会连表一起创建出来,后面每运行一次会创建一条数据
hibernate案例数据库增加数据_第2张图片

调试中出现的问题
hibernate案例数据库增加数据_第3张图片
slf4j的jar包存在不匹配问题,更换jar包后解决问题
hibernate案例数据库增加数据_第4张图片
hibernate.cfg.xml的文件无法找到,需要更换目录到src下
hibernate案例数据库增加数据_第5张图片
jar包缺损找不到导致的问题

Test.java测试类详解
hibernate案例数据库增加数据_第6张图片



你可能感兴趣的:(java_hibernate)