Hibernate
Hibernate是一个开放源代码的对象关系映射框架(O/R对象关系模型),它对JDBC进行了非常轻量级的对象封装,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。
Hibernate说简单点就是把面向关系的编程(sql)转化为面向对象(接口)的方式。
它一端连得是面向对象的,一端连得是面向关系的。
Hibernate就是对JDBC的封装
- JDBC操作数据库很繁琐
- sql语句编写不是面向对象的
- 可以在对象和关系之间建立关联来简化编程
- O/R Mapping 简化编程
- O/R Mapping 跨越数据库平台
O/R说简单点就是有一大堆类库,使用面向对象的方式调用,然后被自动翻译成面向关系的语言。
配置有xml和Annotation两种
Annotation更好用
XML方式
public class Student { private int id; private String name; private int age; 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 int getAge() { return age; } public void setAge(int age) { this.age = age; } }
先配Student.hbm.xml
表示模型与数据表的对照
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.bjsxt.hibernate.Student"> <id name="id" /> <property name="name" /> <property name="age" /> </class> </hibernate-mapping>
再配hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost/hibernate</property> <property name="connection.username">root</property> <property name="connection.password">bjsxt</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">update</property> <mapping resource="com/bjsxt/hibernate/Student.hbm.xml"/> </session-factory> </hibernate-configuration>
Annotation方式
@Entity public class Teacher { private int id; private String name; private String title; @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 getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
不需要Student.hbm.xml这个配置文件
hibernate.cfg.xml的配置前面都一样,只需要最后引入一句即可
<mapping class="com.bjsxt.hibernate.Teacher"/>