原來最流行的web開發三大框架 ssh。現在新出現了ssm。m爲hibernate的替代者——mybatis。
如果是第一次使用數據持久化框架,推薦先使用hibernate,熟悉一些基本的原理,再使用mybatis更順手些。
mybatis爲hibernate的簡化版,如果要使用高級些的功能還推薦使用hibernate。
我使用的是maven項目管理工具。所以引用框架很簡單,加一個dependency即可。
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.8.Final</version>
</dependency>
在src/main/resource文件夾中加入hibernate.cfg.xml的配置文件。並設置數據庫的名稱、用戶名、密碼以及驅動程序
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 各屬性的配置 -->
<property name="show_sql">true</property>
<!-- 一次讀的數據庫記錄數 -->
<property name="jdbc.fetch_size">50</property>
<!-- 設定對數據庫進行批量刪除 -->
<property name="jdbc.batch_size">30</property>
<!--驅動程序 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- JDBC URL -->
<property name="connection.url">jdbc:mysql://localhost/multisensorpositioningsystem?characterEncoding=utf-8</property>
<!-- 數據庫用戶名 -->
<property name="connection.username">root</property>
<!-- 數據庫密碼 -->
<property name="connection.password"></property>
<mapping class="hibernate.User"/>
</session-factory>
</hibernate-configuration>
編寫一個持久化對象,只是pojo加上了一些hibernate的註解
package hibernate;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;
@javax.persistence.Entity
@Table(name = "newsusr")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String userName;
public User() {
super();
// TODO Auto-generated constructor stub
}
public Integer getId() {
此時注意@Entity這個註解是@javax.persistence.Entity。而不是hibernate包下的Entity,如果使用了後者會提示找不到類。
@Entity 註解聲明這是一個持久化類
@Table 指定該類的映射表
@Id 指定標識屬性,標識爲主鍵
@GeneratedValue 用於指定主鍵生成策略IDENTITY爲自動增長
編寫類後記得在hibernate.cfg.xml中加入映射對象的配置
<mapping class="hibernate.User"/>
</session-factory>
因爲hibernate不但支持web應用還支持普通的java application。所以爲我們測試提供了方便。
public static void main(String[] args) {
Configuration conf = new Configuration().configure();
org.hibernate.service.ServiceRegistry service = new StandardServiceRegistryBuilder()
.applySettings(conf.getProperties()).build();
SessionFactory sf = conf.buildSessionFactory(service);
Session sess = sf.openSession();
org.hibernate.Transaction tx = sess.beginTransaction();
User u = new User();
u.setUserName("1312312312312");
sess.save(u);
tx.commit();
sess.close();
sf.close();
}
成功執行後,程序會在控制檯輸出sql語句,因爲我們在hibernate.cfg.xml裏設置了show_sql爲true。設置爲false可以關閉開關。
Hibernate: insert into newsusr (userName) values (?)