利用maven搭建hibernate實例
1、項目結構:
2、配置pom.xml文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lyc.test</groupId>
<artifactId>helloWorld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<!-- hibernate版本號 -->
<hibernate.version>5.1.5.Final</hibernate.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<!-- mysql驅動包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
<!-- hibernate核心jar包 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- hibernate註解 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.0-Final</version>
</dependency>
<!-- Javassist是一款字節碼編輯工具 -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.21.0-GA</version>
</dependency>
<!-- Antlr 是一個基於 Java 開發的功能強大的語言識別工具 -->
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.6</version>
</dependency>
<!-- commons-collections 爲Java標準的Collections API提供了相當好的補充 -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.2</version>
</dependency>
<!-- dom4j是一個Java的XML API -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<!--
1、ORM映射元數據
2、JPA 的API
用來操作實體對象,執行CRUD操作,框架在後臺替我們完成所有的事情,開發者從繁瑣的JDBC和SQL代碼中解
脫出來。
3、查詢語言
-->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
</dependencies>
<build>
<finalName>maven-hibernate-demo</finalName>
</build>
</project>
3、編輯hibernate配置文件hibernate.cfg.xml
<!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="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- url 相當於:jdbc:mysql://localhost:3306/hibernate?useUnicode=true&characterEncoding=UTF-8-->
<property name="connection.url">
<!-- jdbc:mysql:///hibernate?useUnicode=true&characterEncoding=UTF-8這樣寫有問題 -->
<![CDATA[jdbc:mysql://localhost:3306/hibernate?useUnicode=true&characterEncoding=utf8]]>
</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- hibernate可選項信息 -->
<!-- 數據庫方言 -->
<property name="dialect">
org.hibernate.dialect.MySQL5Dialect
</property>
<!-- 是否打印sql語句 -->
<property name="show_sql">true</property>
<!-- 格式化sql語句 -->
<property name="format_sql">true</property>
<!-- 數據庫更新方式:
create:每次執行 都先把原有數據表刪除,然後創建該表
create-drop:使用 create-drop時,在顯式關閉SessionFactory時,
將drop掉數據庫schema(表).
validate:檢測
update:如果表不存在 則創建,有就不用創建
-->
<property name="hbm2ddl.auto">update</property>
<!-- 映射文件信息 -->
<mapping resource="com/lyc/pojo/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
4、創建實體類User
package com.lyc.pojo;
public class User {
private int id;
private String name;
private String pwd;
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 getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return this.id+this.name+this.pwd;
}
}
並編輯對應的映射文件User.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">
<!-- package聲明pojo類所在的包,如果不寫 那麼在class中需要指明pojo類所在的包
schema指數據庫模式 一個模式下可以有多張表
-->
<hibernate-mapping package="com.lyc.pojo" >
<!-- class指映射一個pojo類
提供了公共的無參構造方法-通過反射產生對象
屬性用private修飾,並且生成對應的get/set方法
類不能用final來修飾-hibernate會產生代理類(cglib)
類需要指明標識
name表示pojo類名
table表示pojo類對應數據庫中的表名;如果不寫默認是類名
-->
<class name="User" table="user">
<!--
id表示實體類的標識(OID)
對應數據庫表中的主鍵
name指實體類的標識屬性名
column表示對應數據庫表的列名:如果不寫 則數據庫表中列名和屬性名一致
length表示數據庫表中 對應數據類型的長度 ,如果不寫有默認長度
type表示類型如果不寫hibernate可以找到對應pojo類的屬性的類型
-->
<id name="id" column="id">
<!-- 主鍵生成策略
increment 用於爲long, short或者int類型生成 唯一標識。
只有在沒有其他進程往同一張表中插入數據時才能使用。 在集羣下不要使用
(mysql,ms sql)
identity 對DB2,MySQL, MS SQL Server, Sybase和HypersonicSQL
的內置標識字段提供支持。 返回的標識符是long, short 或者int類型的。
sequence 在支持序列的數據庫中使用 oracle
<generator class="sequence">
<param name="sequence">user_seq</param>
</generator>
uuid UUID被編碼爲一個32位16進制數字的字符串。
native 根據底層數據庫的能力選擇identity, sequence 或者hilo中的一個。
assigned 自己指定主鍵
-->
<generator class="native"/>
</id>
<!-- 實體類的屬性
name:指明 pojo類屬性名稱(區分大小寫)
-->
<property name="name">
<column name="name"></column>
</property>
<property name="pwd"/>
</class>
</hibernate-mapping>
5、編寫測試類
package com.lyc.hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.junit.Test;
import com.lyc.pojo.User;
public class HibernateTest {
@Test
public void testHibernate(){
Configuration cfg = null;
SessionFactory sf = null;
Session session = null;
Transaction tx = null;
try{
cfg = new Configuration().configure();
ServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
sf = cfg.buildSessionFactory(registry);
session = sf.openSession();
tx = session.beginTransaction();
User user = new User();
user.setName("咪咪");
user.setPwd("1111");
session.save(user);
//6.提交事務
tx.commit();
}catch (Exception e) {
e.printStackTrace();
//回滾事務
tx.rollback();
throw new HibernateException(e.getCause());
}finally{
//7.關閉session
if(session!=null&&session.isOpen())
session.close();
sf.close();
}
}
}
至此利用maven搭建好了一個hibernate項目
運行結果: