搜尋
首頁資料庫mysql教程简单的Hibernate访问数据库Demo

简单的Hibernate访问数据库Demo

Jun 07, 2016 pm 04:10 PM
demohibernate學習資料庫簡單訪問

最近在学习SSH,现在看到Hibernate这块,动手实现了一个简单的Demo,对Hibernate的功能、使用有了初步了解。 1、首先将Hibernate的jar包复制到Web项目的lib目录下。有些依赖jar包,要额外导入;比如cglib-nodep.jar,不然会报错。 2、配置实体类。这里我用的

最近在学习SSH,现在看到Hibernate这块,动手实现了一个简单的Demo,对Hibernate的功能、使用有了初步了解。

1、首先将Hibernate的jar包复制到Web项目的lib目录下。有些依赖jar包,要额外导入;比如cglib-nodep.jar,不然会报错。

2、配置实体类。这里我用的是一个简单Account类,要注意使用的是javax.persistense.*下面的注解,不是org.hibernate.*下的。

 

package com.jobhelp.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity		//@Entity表示该类能被hibernate持久化
@Table(name="user")		//指定Entity对应的数据表名
public class Account {
	
	@Id		//指定该列为主键
	@GeneratedValue(strategy=GenerationType.AUTO)	//auto为自增长
	private Integer id;
	
	@Column(name="name")
	private String username;
	
	@Column(name="password")
	private String password;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

}

3、在src目录下新建Hibernate的配置文件hibernate.cfg.xml。(MyEclipse向导会自动生成,我用的是Eclipse,就得自己创建了。)

 

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配置的,SessionFactory是Hibernate中的一个类,这个类主要负责保存HIbernate的配置信息,以及对Session的操作 -->
	<session-factory>
		<!--配置数据库的驱动程序,Hibernate在连接数据库时,需要用到数据库的驱动程序 -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver </property>
		<!--设置数据库的连接url:jdbc:mysql://localhost/hibernate,其中localhost表示mysql服务器名称,此处为本机, 
			hibernate是数据库名 -->
		<property name="hibernate.connection.url">
			jdbc:mysql://localhost/User
		</property>
		<!--连接数据库是用户名 -->
		<property name="hibernate.connection.username">root </property>
		<!--连接数据库是密码 -->
		<property name="hibernate.connection.password">123456 </property>
		<!--数据库连接池的大小 -->
		<property name="hibernate.connection.pool.size">20 </property>
		<!--是否在后台显示Hibernate用到的SQL语句,开发时设置为true,便于差错,程序运行时可以在Eclipse的控制台显示Hibernate的执行Sql语句。项目部署后可以设置为false,提高运行效率 -->
		<property name="hibernate.show_sql">true </property>
		<!--jdbc.fetch_size是指Hibernate每次从数据库中取出并放到JDBC的Statement中的记录条数。Fetch Size设的越大,读数据库的次数越少,速度越快,Fetch 
			Size越小,读数据库的次数越多,速度越慢 -->
		<property name="jdbc.fetch_size">50 </property>
		<!--jdbc.batch_size是指Hibernate批量插入,删除和更新时每次操作的记录数。Batch Size越大,批量操作的向数据库发送Sql的次数越少,速度就越快,同样耗用内存就越大 -->
		<property name="jdbc.batch_size">23 </property>
		<!--jdbc.use_scrollable_resultset是否允许Hibernate用JDBC的可滚动的结果集。对分页的结果集。对分页时的设置非常有帮助 -->
		<property name="jdbc.use_scrollable_resultset">false </property>
		<!--connection.useUnicode连接数据库时是否使用Unicode编码 -->
		<property name="Connection.useUnicode">true </property>
		<!--connection.characterEncoding连接数据库时数据的传输字符集编码方式,最好设置为gbk,用gb2312有的字符不全 -->
		<!--  <property name="connection.characterEncoding">gbk </property>-->

		<!--hibernate.dialect 只是Hibernate使用的数据库方言,就是要用Hibernate连接那种类型的数据库服务器。 -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect </property>
		<!--指定映射文件为&ldquo;hibernate/ch1/UserInfo.hbm.xml&rdquo; -->
		<!-- <mapping resource="org/mxg/UserInfo.hbm.xml"> -->
		<mapping class="com.jobhelp.domain.Account"></mapping>
	</session-factory>
</hibernate-configuration>

4、新建Hibernate工具类,用于获取session。Hibernate中每一个session代表一次完整的数据库操作。

 

Hibernate官方提供的HibernateUtil.java

 

package com.jobhelp.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {

	private static final SessionFactory sessionFactory;//单例模式的SessionFactory
	
	//static代码块,类加载时初始化hibernate,单例只初始化一次
	static{
		try{
			//从hibernate.cfg.xml中加载配置
			//加载@注解配置的实体类用AnnotationConfiguration()
			//加载xml配置的实体类使用Configuration()
			sessionFactory = new AnnotationConfiguration()
						.configure("hibernate.cfg.xml").buildSessionFactory();
		} catch (Throwable ex){
			System.err.println("Initial SessionFactory Error");
			throw new ExceptionInInitializerError(ex);
		}
	}
	
	public static SessionFactory getSessionFactory(){
		return sessionFactory;
	}
}

5、初始化MySql数据库,建一个简单的User表即可,我用的表数据如下。

 

 

mysql> select * from user;
+----+-------+----------+
| id | name  | password |
+----+-------+----------+
|  1 | admin | 123456   |
|  2 | bowen | 123456   |
|  3 | tom   | 123456   |
|  4 | jack  | 123456   |
+----+-------+----------+

6、执行hibernate程序。Hibernate是ORM框架,与数据库打交道。

 

Hibernate中session会话与JDBC操作数据库流程差不多。

相对Spring中jdbcTemplate的使用,hibernate不用写sql语句,不用封装结果;逻辑清晰,代码简洁很多,显然有利于提高开发效率。

下面是在一个Test类中,执行了Hibernate程序的代码。

 

package com.jobhelp.util;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.jobhelp.domain.Account;

public class Test {
	
	public static void main(String[] agrs){
		/*Account account =new Account();
		account.setUsername("jack");
		account.setPassword("123456");*/
		
		//start a hibernate session
		Session session = HibernateUtil.getSessionFactory().openSession();
		//start a transaction
		Transaction transaction = session.beginTransaction();
		
		//insert into database
		//session.persist(account);
		
		@SuppressWarnings("all")
		//hql query
		List<Account> list =session.createQuery("from Account").list();
		
		//print query result
		for(Account account2: list){
			System.out.println(account2.getId()+" : "+account2.getUsername());
		}
		
		transaction.commit();
		session.close();
	}

}
执行结果:

 

 

[2014-11-24 21:26:19,083][DEBUG][org.hibernate.jdbc.AbstractBatcher:366] - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
[2014-11-24 21:26:19,083][DEBUG][org.hibernate.SQL:401] - select account0_.id as id0_, account0_.password as password0_, account0_.name as name0_ from user account0_
Hibernate: select account0_.id as id0_, account0_.password as password0_, account0_.name as name0_ from user account0_
......
[2014-11-24 21:26:19,108][DEBUG][org.hibernate.engine.StatefulPersistenceContext:787] - initializing non-lazy collections
1 : admin
2 : bowen
3 : tom
4 : jack
[2014-11-24 21:26:19,109][DEBUG][org.hibernate.transaction.JDBCTransaction:103] - commit
......

注意:Hibernate只会生成表结构,但不会创建数据库。如果指定数据库不存在,hibernate会抛出异常。

 

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
在MySQL中使用視圖的局限性是什麼?在MySQL中使用視圖的局限性是什麼?May 14, 2025 am 12:10 AM

mysqlviewshavelimitations:1)他們不使用Supportallsqloperations,限制DatamanipulationThroughViewSwithJoinsOrsubqueries.2)他們canimpactperformance,尤其是withcomplexcomplexclexeriesorlargedatasets.3)

確保您的MySQL數據庫:添加用戶並授予特權確保您的MySQL數據庫:添加用戶並授予特權May 14, 2025 am 12:09 AM

porthusermanagementinmysqliscialforenhancingsEcurityAndsingsmenting效率databaseoperation.1)usecReateusertoAddusers,指定connectionsourcewith@'localhost'or@'%'。

哪些因素會影響我可以在MySQL中使用的觸發器數量?哪些因素會影響我可以在MySQL中使用的觸發器數量?May 14, 2025 am 12:08 AM

mysqldoes notimposeahardlimitontriggers,butacticalfactorsdeterminetheireffactective:1)serverConfiguration impactactStriggerGermanagement; 2)複雜的TriggerSincreaseSySystemsystem load; 3)largertablesslowtriggerperfermance; 4)highConconcConcrencerCancancancancanceTigrignecentign; 5); 5)

mysql:存儲斑點安全嗎?mysql:存儲斑點安全嗎?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

mySQL:通過PHP Web界面添加用戶mySQL:通過PHP Web界面添加用戶May 14, 2025 am 12:04 AM

通過PHP網頁界面添加MySQL用戶可以使用MySQLi擴展。步驟如下:1.連接MySQL數據庫,使用MySQLi擴展。 2.創建用戶,使用CREATEUSER語句,並使用PASSWORD()函數加密密碼。 3.防止SQL注入,使用mysqli_real_escape_string()函數處理用戶輸入。 4.為新用戶分配權限,使用GRANT語句。

mysql:blob和其他無-SQL存儲,有什麼區別?mysql:blob和其他無-SQL存儲,有什麼區別?May 13, 2025 am 12:14 AM

mysql'sblobissuitableForStoringBinaryDataWithInareLationalDatabase,而ilenosqloptionslikemongodb,redis和calablesolutionsolutionsolutionsoluntionsoluntionsolundortionsolunsonstructureddata.blobobobissimplobisslowdeperformberbutslowderformandperformancewithlararengedata;

mySQL添加用戶:語法,選項和安全性最佳實踐mySQL添加用戶:語法,選項和安全性最佳實踐May 13, 2025 am 12:12 AM

toaddauserinmysql,使用:createUser'username'@'host'Indessify'password'; there'showtodoitsecurely:1)choosethehostcarecarefullytocon trolaccess.2)setResourcelimitswithoptionslikemax_queries_per_hour.3)usestrong,iniquepasswords.4)Enforcessl/tlsconnectionswith

MySQL:如何避免字符串數據類型常見錯誤?MySQL:如何避免字符串數據類型常見錯誤?May 13, 2025 am 12:09 AM

toAvoidCommonMistakeswithStringDatatatPesInMysQl,CloseStringTypenuances,chosethirtightType,andManageEngencodingAndCollat​​ionsEttingSefectery.1)usecharforfixed lengengtrings,varchar forvariable-varchar forbariaible length,andtext/blobforlargerdataa.2 seterters seterters seterters

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具