Hibernate curd 小例題
hibernate操作步驟
實現以下功能
有一個學生表
學號 姓名 年齡 地址 電話
實現 新增學生 查詢所有學生資訊 根據學號刪除學生 根據學號修改學生資訊
1、匯入jar
將oracle安裝目錄中的jar 通過maven命令 安裝到本地倉庫
2、maven命令安裝到本地倉庫
Mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.1.0 -Dpackaging=jar -Dfile=D:\jar\ojdbc6.jar |
3、在pom.xml中新增座標
<dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.0.1.0</version> </dependency> |
4、新增hibernate的座標
不想自己導jar可以改一下版本號,從阿里雲下載的jar包
<!-- https://mvnrepository.com/artifact/ojdbc/ojdbc --> <!-- |
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-nop --><dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-nop</artifactId> <version>1.7.25</version> <scope>test</scope> </dependency><!-- https://mvnrepository.com/artifact/log4j/log4j --><dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- https://mvnrepository.com/artifact/org.jboss.logging/jboss-logging --><dependency> <groupId>org.jboss.logging</groupId> <artifactId>jboss-logging</artifactId> <version>3.3.0.Final</version> </dependency> |
5、建立hibernate配置檔案 預設名字為: hibernate.cfg.xml
a.從參考文件中copy(檔案頭別忘了)
b.修改對應的資料庫連線
c.註釋暫時用不上的內容
<?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> <!-- Database connection settings --> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver </property> <property name="connection.url" >jdbc:oracle:thin:@localhost:1521:orcl</property> <property name="connection.username" >scott</property> <property name="connection.password">tiger</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size" >1</property> <!-- SQL dialect 方言 --> <property name="dialect" >org.hibernate.dialect.Oracle10gDialect</property> <!-- Enable Hibernate's automatic session context management 執行緒 單執行緒 --> <!-- 在程式碼中獲取session有兩種方式,其中一種需要新增該配置 --> <property name="current_session_context_class" >thread </property> <!-- Echo all executed SQL to stdout --> <!-- 在控制檯輸出sql --> <property name="show_sql" >true </property> <!-- Drop and re-create the database schema on startup --> <!-- 策略 --> <property name="hbm2ddl.auto" >update </property> <!-- 註解mapping檔案 --> <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/> </session-factory> </hibernate-configuration> |
6、建立持久化類
a.對資料庫student表進行操作
b.建立包com.vp.pojo
c. 建立實體類 Student
package com.vp.pojo; import java.io.Serializable; import java.util.Objects;/** * @Description: * @Author: Li.Hong.Yue * @Establish: 2018-10-23 20:38 **/public class Student implements Serializable{ private Integer stuid; private String stuname; private Integer age; private String address; private String phone; public Integer getStuid() { return stuid; } public void setStuid(Integer stuid) { this.stuid = stuid; } public String getStuname() { return stuname; } public void setStuname(String stuname) { this.stuname = stuname; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return Objects.equals( getStuid(), student.getStuid() ) && Objects.equals( getStuname(), student.getStuname() ) && Objects.equals( getAge(), student.getAge() ) && Objects.equals( getAddress(), student.getAddress() ) && Objects.equals( getPhone(), student.getPhone() ); } @Override public int hashCode() { return Objects.hash( getStuid(), getStuname(), getAge(), getAddress(), getPhone() ); } @Override public String toString() { return "Student{" + "stuid=" + stuid + ", stuname='" + stuname + '\'' + ", age=" + age + ", address='" + address + '\'' + ", phone='" + phone + '\'' + '}'; } } |
7、建立Student類的對映文 Student.hbm.xml(在該類的包下面建立)
a.參考文件copy(檔案頭別忘了)
b.id元素中填寫主鍵
c. generator取值範圍"native"由Hibernate根據使用的資料庫自行判斷採用identity、hilo、sequence其中一種作為主鍵生成方式。
d.欄位名與列名相同,列名可以省略不寫(表名一樣)
<?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="com.vp.pojo"> <class name="Student"> <id name="stuid" > <generator class="native"/> </id> <property name="stuname" /> <property name="age" /> <property name="address" /> <property name="phone"/> </class> </hibernate-mapping> |
8、將對映檔案加入到配置檔案hibernate.cfg.xml中.
a.參考文件
b. <mapping resource="com/hibernate/pojo/ Student.hbm.xml" />
9、編寫測試類 Main 在Main中對Dept表進行操作
a.參考文件
b.建立工具類
package com.vp.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; /** * @Description: * @Author: Li.Hong.Yue * @Establish: 2018-10-23 20:58 **/ public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } } |
c.測試類
public static void main( String[] args ) { System.out.println( "Hello World!" ); Session session= HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); /*Student student=new Student();*/ /*新增*/ /*student.setStuid( 5 ); student.setStuname( "C" ); student.setAge( 19 ); student.setAddress( "CC" ); student.setPhone( "1774853165" ); session.save( student );*/ /*刪除*/ /*student.setStuid( 5 ); session.delete( student );*/ /*更新*/ /*student.setStuid( 4 ); student.setStuname( "哈哈" ); student.setAge( 19 ); student.setAddress( "哈哈" ); student.setPhone( "1774853165" ); session.update( student );*/ /*單個查詢*/ Student student=(Student)session.get( Student.class,1 ); System.out.println("student:"+student); session.getTransaction().commit(); HibernateUtil.getSessionFactory().close(); } |