標籤:資料 圖片 setter 對象 mysql java程式員 pre tac www.
Hibernate是一個開放原始碼的對象關係映射架構,它對JDBC進行了非常輕量級的對象封裝,它將POJO與資料庫表建立映射關係,是一個全自動的orm架構,hibernate可以自動產生SQL語句,自動執行,使得Java程式員可以隨心所欲的使用對象編程思維來操縱資料庫。
ORM: Object Realtion Mapping
一,匯入jar包
二,建立資料庫,建表
三,建立class,和表的對應關係對應檔
Account.class
public class Account {/* 一定要產生 setter getter 方法,否則包異常 */private int accountId;private String name;private int age;private String nickName;public int getAccountId() {return accountId;}public void setAccountId(int accountId) {this.accountId = accountId;}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 String getNickName() {return nickName;}public void setNickName(String nickName) {this.nickName = nickName;}}
Account.hbm.xml
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="gy.hibernate"><class name="Account" table="accounts"><!-- 主鍵 ,映射 --><id name="accountId" column="id"><generator class="native" /></id><!-- 非主鍵,映射 --><property name="name" column="name"></property><property name="age" column="age"></property><property name="nickName" column="nick_name"></property></class></hibernate-mapping>
四,配置hibernate 設定檔
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><!-- 資料庫連接配置 --><!-- 設定資料庫驅動 --><property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property><!-- 設定資料庫url --><property name="hibernate.connection.url">jdbc:mysql:///hibernate_db</property><!-- mysql帳號 --><property name="hibernate.connection.username">root</property><!-- mysql密碼 --><property name="hibernate.connection.password"></property><property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property><!-- 調試列印日誌 --><property name="hibernate.show_sql">true</property><!-- 載入所有映射 --><mapping resource="gy/hibernate/Account.hbm.xml"/></session-factory></hibernate-configuration>
五,代碼調用
public String register() { System.out.println("開始註冊-------------------------"); Account account = new Account(); // account.setAccountId(1); account.setName("xiao gang"); account.setAge(15); account.setNickName("xg"); // 擷取載入設定檔的管理類對象 Configuration config = new Configuration(); config.configure(); // 預設載入src/hibenrate.cfg.xml檔案 // 建立session的工廠對象 SessionFactory sf = config.buildSessionFactory(); // 建立session (代表一個會話,與資料庫連接的會話) Session session = sf.openSession(); // 開啟事務 Transaction tx = session.beginTransaction(); // 儲存-資料庫 session.save(account); // 提交事務 tx.commit(); // 關閉 session.close(); sf.close(); return SUCCESS; }
(28)java web的hibernate使用