– Start
下面我们来看一下如何通过 Hibernate 访问数据库。通过与 JDBC 对比我们发现,通过 Hibernate 访问数据库可以使我们以面向对象的方式访问数据库,Hibernate 是如何做到的呢?中心思想就是把表和对象映射起来,我们只需要面向对象进行操作,Hibernate 会转成 SQL 对数据库进行操作,这就是所谓的 ORM (Object/Relational Mapping),那如何把表和对象映射起来呢?有两种方法,一种是通过 xml,如下面的例子演示的那样,另一种方法是通过注解,我们下回分解。
package shangbo.hibernate.demo002;
/*
* 通过 Hibernate 访问数据库
*/
public class App {
public static void main(String[] args) throws Exception {
DataService dataService = new DataService();
dataService.saveCustomer(new Customer(2, "test"));
}
}
package shangbo.hibernate.demo002;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class Da