Hibernate是一個開源的ORM框架,顧名思義,它的核心思想即ORM(Object Relational Mapping,物件關係映射),可以透過物件來操作資料庫中的信息,據說開發者一開始是不太熟悉資料庫SQL語句的,這也造就了hibernate的強大之處,它不強求開發者熟悉SQL語句也可以操作資料庫,hibernate可以自動產生SQL語句,自動執行。
利用hibernate可以讓開發者完全使用面想物件思維來操作資料庫,所以接下來的示範不會有一句SQL語句,如果有的話,請當我這句話沒說!
本文使用hibernate實作了簡單的一個person資料表的基本增刪改查操作。
環境:win7+eclipse
工具包:hibernate包,可前往下載,本例中使用的是4版本;
資料庫連線驅動程式包,本範例使用的是mysql的
package demo.pojo; public class Person {private Integer id;private String name;private String gender;private Integer age;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 String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "Person [id=" + id + ", name=" + name + ", gender=" + gender + ", age=" + age + "]";}}
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 以下四行分别为:数据库驱动类、Drivermanager获取连接的参数URL、用户名、密码 --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://127.0.0.1/web?characterEcoding=utf-8</property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <!-- 设置方言,hibernate会根据数据库的类型相应生成SQL语句 --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 控制台显示生成的sql语句,默认为false --> <property name="show_sql">true</property> <!-- 映射配置源文件的位置 --> <mapping resource="demo/pojo/Person.hbm.xml"/> </session-factory> </hibernate-configuration>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <!-- name是实体类全名,table为数据表名 --> <class name="demo.pojo.Person" table="Person"> <id name="id" column="id"> <!-- 主键生成方式,native是让hibernate自动识别 --> <generator class="native"></generator> </id> <!--
# 注意點:
0.name值為實體類別中屬性名,column為資料表中欄位名稱;
1.當實體類別中屬性名稱與對應資料表欄位名稱相同時,後面的column可以省略,hibernate會自動匹配,例如下面age ;
2.反之當實體類別中屬性名稱與對應資料表欄位名稱不相同時,兩項都要寫上,例如下面gender和sex
-->
<property name="name" column="name"></property> <property name="gender" column="sex"></property> <property name="age"></property> </class> </hibernate-mapping>
package demo.util; import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;import org.hibernate.service.ServiceRegistry;import org.hibernate.service.ServiceRegistryBuilder; public class HibernateSessionFactory {private static SessionFactory factory;private static ThreadLocal<Session> thread = new ThreadLocal<Session>();private static String path = "hibernate.cfg.xml";private static Configuration config = new Configuration();static {config.configure(path);ServiceRegistry service = new ServiceRegistryBuilder()//定义一个服务注册机.applySettings(config.getProperties()).buildServiceRegistry();factory = config.buildSessionFactory(service);//创建Session工厂类}/** * 从hibernate的session工厂类里创建一个session * @return * */public static Session getSession() {Session session = thread.get();if(session == null || !session.isOpen()) {session = factory.openSession();thread.set(session);}return session;}public static void closeSession() {Session session = thread.get();if(session != null && session.isOpen()) {session.close();thread.set(null);}}}
package demo.dao; import java.io.Serializable;import org.hibernate.Session;import org.hibernate.Transaction;import demo.pojo.Person;import demo.util.HibernateSessionFactory; public class PersonDaoImpl {//增删改查,此处以增为例public boolean add(Person p) {Session session = HibernateSessionFactory.getSession();//创建SessionTransaction trans = session.beginTransaction();//开启事务try {Serializable id = session.save(p);//添加记录并获取主键值System.out.println(id+"为获取的主键值");//控制台查看主键值trans.commit();//提交事务return true;} catch (Exception e) {trans.rollback();//获取异常,则事务回滚} finally {HibernateSessionFactory.closeSession();//关闭Session}return false;}}
package demo.test; import org.junit.Test;import demo.dao.PersonDaoImpl;import demo.pojo.Person; public class TestPerson {@Testpublic void testAdd() {//创建一个人类对象Person p = new Person();p.setName("张三");p.setGender("男");p.setAge(18);//创建dao层类对象并调用添加方法PersonDaoImpl dao = new PersonDaoImpl();dao.add(p);}}
#
以上是使用hibernate實作person資料表的操作的詳細內容。更多資訊請關注PHP中文網其他相關文章!