hibernate配置(hibernate5):调试Hibernate 程序所需要的基本Jar 包,在Hibernate 框架解压目录的lib 目录下。
(1)reqired 目录下所有Jar
(2)optional/c3p0 目录下所有Jar
(3)optional/ehcache/slf4j-api-1.6.1.jar
(4)jpa-metamodel-generator 目录下所有Jar
(5)jpa/hibernate-entitymanager-5.0.1.Final.jar
当然,还需要一些其它的辅助Jar 包。
(1)junit-4.9.jar
(2)slf4j-log4j12-1.7.12.jar 与log4j-1.2.17.jar
(3)mysql 驱动
public class Student { private Integer id; private String name; private int age; private double score; public Student() { super(); // TODO Auto-generated constructor stub } public Student(String name, int age, double score) { super(); this.name = name; this.age = age; this.score = score; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", age=" + age + ", score=" + score + "]"; } //getter and setter 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; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } }
(1)找到以下DTD文件:
(2)打开hibernate-mapping-3.0.dtd,复制:
(3)在Student同目录下新建Student.hbm.xml:
(1)找到以下DTD文件:
(2)打开hibernate-configuration-3.0.dtd,复制:
(3)在src目录下新建hibernate.cfg.xml:
com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/hibernate5 root 123456 thread true true org.hibernate.dialect.MySQLDialect org.hibernate.c3p0.internal.C3P0ConnectionProvider create
public class Test { public static void main(String[] args) { //加载主配置文件与映射文件 Configuration configure = new Configuration().configure(); //创建session工厂对象 SessionFactory sessionFactory = configure.buildSessionFactory(); //开启Session对象 Session session = sessionFactory.getCurrentSession(); try { //开启事务 session.beginTransaction(); Student student = new Student("张三",23,93.5); //执行操作 session.save(student); //提交事务 session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); //回滚事务 session.getTransaction().rollback(); } } }