當前位置:首頁 » 操作系統 » hibernate連接mysql資料庫

hibernate連接mysql資料庫

發布時間: 2022-05-06 23:41:41

Ⅰ mysql+hibernate

主要是斷開連接到MySQL釋放連接有一定的等待時間,是你短時間不斷連接造成的。就像TCP/IP協議裡面的連接,客戶端斷開後,伺服器不是立刻清除,而通常是出於TIME_WAIT狀態,一定時間之後才會斷開。
Hibernate裡面,應該自己構造會話工廠,用靜態方法或者變數保存自己的會話。

如:

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {

/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "/com/sxws/chis/object/hibernate/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;

static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}

/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();

if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}

return session;
}

/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}

/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);

if (session != null) {
session.close();
}
}

/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}

/**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}

/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}

}

Ⅱ hibernate怎麼連接mysql資料庫

首先,我們把hibernate最基本的資料庫連接,使用mysql。
見一個java工程,見一個包名為book,
在book的包下加一個java類Book.java,其代碼如下:
package
book;
public
class
Book
{
private
Integer
id;
private
String
name;
private
String
writer;
public
Integer
get
hibernate最基本的資料庫連接,使用mysql。
見一個java工程,見一個包名為「book」

Ⅲ Hibernate中連MySQL資料庫,連接不了

<property
name="hibernate.connection.username">'root'</property>
<property
name="nibernate.connection.password">'admin'</property>
從錯誤信息來看,是PWD不對,這里來看的話,你是用的root許可權登陸MySQL,密碼是否正確?你用MySQL客戶端登陸的話是用的這個密碼嗎?
另外看你的hibernate配置文件中這里username和password為什麼要加個單引號?把這個單引號去掉試試。

Ⅳ hirbernate怎麼連接mysql資料庫

首先,我們把hibernate最基本的資料庫連接,使用mysql。 見一個java工程,見一個包名為book, 在book的包下加一個java類Book.java,其代碼如下: package book; public class Book { private Integer id; private String name; private String writer; public Integer get hibernate最基本的資料庫連接,使用mysql。 見一個java工程,見一個包名為「book」
溫馨提示:下圖僅供欣賞,不作為教學。

然後在在book的包下加一個java類Book.java,其代碼如下: package book; public class Book { private Integer id; private String name; private String writer; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getWriter() { return writer; } public void setWriter(String writer) { this.writer = writer; } }
溫馨提示:下圖僅供欣賞,不作為教學。

Ⅳ Hibernate如何動態鏈接資料庫

一.導包 mysql
二.在默認src下創建hibernate.cfg.xml
1.創建xml文件,命名為hibernate.cfg.xml
2.添加約束
(在org.hibernate/hibernate-configuration-3.0.dtd中)
1 <!DOCTYPE hibernate-configuration PUBLIC2 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"3 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration> <session-factory> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.url">jdbc:mysql://localhost:3306/houserentsys</property> <!-- houserentsys是資料庫名稱 -->

<property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.username">root</property> <property name="connection.password">123456</property>
<property name="show_sql">true</property> <property name="format_sql">false</property> <!-- 設置為false就會不換行 --> <property name="hbm2ddl.auto">update</property> <!-- 進行操作時不會刪除重建-->

<!--hbm2ddl.auto屬性:

create:表示啟動的時候先drop,再create
c
reate-drop: 也表示創建,只不過再系統關閉前執行一下drop

update: 這個操作啟動的時候會去檢查schema是否一致,如果不一致會做scheme更新

validate: 啟動時驗證現有schema與你配置的hibernate是否一致,如果不一致就拋出異常,並不做更新
-->
<mapping resource="e/tsinghua/entity/mapping/district.xml"/> <mapping resource="e/tsinghua/entity/mapping/street.xml"/>
</session-factory></hibernate-configuration>

hbm2ddl.auto屬性:
create:表示啟動的時候先drop,再create
create-drop: 也表示創建,只不過再系統關閉前執行一下drop
update: 這個操作啟動的時候會去檢查schema是否一致,如果不一致會做scheme更新
validate: 啟動時驗證現有schema與你配置的hibernate是否一致,如果不一致就拋出異常,並不做更新
三.實體 實現序列化介面 封裝屬性和構造方法 實體.xml 位置隨意
(在org.hibernate/hibernate-mapping-3.0.dtd中)
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
在hibernate.cfg.xml 添加 映射文件的引用
<mapping resource="e.tsinghua.entity.mapping.district"/>
七個步驟(在新建的執行文件Test.java中)
//1.載入配置文件
Configuration cfg=new Configuration().configure();
//2.獲得sessionfactory
ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
SessionFactory sf=cfg.buildSessionFactory(serviceRegistry);
//3.創建session
Session session=sf.openSession();
//4.創建事務
Transaction tx=session.beginTransaction();
//5.操作
District dis=new District(100,"海淀區");
session.save(dis);
//6.提交 回滾
tx.commit();//tx.rollback();
//7.釋放資源

Ⅵ 如何使用hibernate與mysql資料庫進行連接

方法/步驟

首先,我們把hibernate最基本的資料庫連接,使用mysql。
見一個java工程,見一個包名為book, 在book的包下加一個java類Book.java,其代碼如下: package book;
public class Book { private Integer id; private String name; private
String writer; public Integer get hibernate最基本的資料庫連接,使用mysql。
見一個java工程,見一個包名為「book」

然後在在book的包下加一個java類Book.java,其代碼如下:
package book; public class Book { private Integer id; private
String name; private String writer; public Integer getId() {
return id; } public void setId(Integer id) { this.id = id;
} public String getName() { return name; } public void
setName(String name) { this.name = name; } public String
getWriter() { return writer; } public void setWriter(String
writer) { this.writer = writer; } }
溫馨提示:下圖僅供欣賞,不作為教學。

然後在book包下建一個book.hbm.xml,其代碼如下:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="book" default-lazy="false">
<class name="Book"> <id name="id"> <generator
class="increment"/> </id> <property name="name"
></property> <property name="writer"
></property> </class> </hibernate-mapping>
溫馨提示:下圖僅供欣賞,不作為教學。

這個事與資料庫裡面的欄位名形成映射關系,自己在mysql建立book表時與之對應,id是自增長的,
然後在工程的根目錄下建一個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="connection.driver_class">com.mysql.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://localhost/mydb</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property
name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property> <!--
<property
name="hbm2ddl.auto">${hibernate.hbm2ddl.auto}</property>-->
<!-- <property
name="current_session_context_class">thread</property>-->
<mapping resource="book/Book.hbm.xml" />
</session-factory> </hibernate-configuration>
溫馨提示:下圖僅供欣賞,不作為教學。

這是連接mysql資料庫的,用戶名和密碼改為你mysql資料庫的
<property name="show_sql">true</property>這是在後台列印sql語句
<mapping resource="book/Book.hbm.xml" />這是找到映射文件。
溫馨提示:下圖僅供欣賞,不作為教學。

然後些個測試類:代碼如下:
package test; import org.hibernate.Session; import
org.hibernate.SessionFactory; import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration; import book.Book; public
class MainTest { /** * @param args */ public static void
main(String[] args) { try { Configuration cfg=new
Configuration()。configure(); SessionFactory
sf=cfg.buildSessionFactory(); Session session = sf.openSession();
Transaction ts=session.beginTransaction(); Book b=new Book();
b.setName("hibernate"); b.setWriter("div"); session.save(b); //
Book b=(Book) session.get(Book.class,1); // if(b!=null){ //
b.setName("xujun"); // System.out.println("書名為:"+b.getName()); //
System.out.println("作者為:"+b.getWriter()); // session.delete(b); //
} ts.commit(); session.close(); sf.close(); } catch
(Exception e) { e.printStackTrace(); } } }

mysql表的欄位如下:

把資料庫建好後就可以測試。對了,關鍵的還沒有說,還得把antlr.jar,cglib.jar,asm.jar,asm-attrs.jar,commons-colletions.jar,commons-logging.jar,ehcache.jar,
jta.jar,dom4.jar,log4.jar,hibernate3.jar引入到lib目錄下

Ⅶ hibernate與資料庫連接的幾種方式

三種連接都是以連接MySQl為例。

<!-- JDBC驅動程序 -->
<property name="connection.driver_class">org.gjt.mm.mysql.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/struts?useUnicode=true&characterEncoding=GBK</property> <!-- 資料庫用戶名 -->
<property name="connection.username">root</property> <!-- 資料庫密碼 -->
<property name="connection.password">8888</property>

上面的一段配置,在c3p0和dbcp中,都是必需的,因為hibernate會根據上述的配置來生成connections,再交給c3p0或dbcp管理.但是,proxool則不能,雖然說服文檔上說proxool也可以和hibernate結合,但我按照官方文檔上的說明怎麼配也出錯,而且,到了sun和hibernat有的官方網站上問了幾天,都沒有一個人回復。後來我只能讓proxool自身來生成連接,這在下面再講。

1 C3P0

只需在hibernate.cfg.xml中加入
<property name="c3p0.min_size">5</property>
<property name="c3p0.max_size">30</property>
<property name="c3p0.time_out">1800</property>
<property name="c3p0.max_statement">50</property>

還有在classespath中加入c3p0-0.8.4.5.jar

2 dbcp

在hibernate.cfg.xml中加入

<property name="dbcp.maxActive">100</property>
<property name="dbcp.whenExhaustedAction">1</property>
<property name="dbcp.maxWait">60000</property>
<property name="dbcp.maxIdle">10</property>

<property name="dbcp.ps.maxActive">100</property>
<property name="dbcp.ps.whenExhaustedAction">1</property>
<property name="dbcp.ps.maxWait">60000</property>
<property name="dbcp.ps.maxIdle">10</property>

還有在classespath中加入commons-pool-1.2.jar 和commons-dbcp-1.2.1.jar.

3 proxool

在hibernate.cfg.xml中加入

<property name="proxool.pool_alias">pool1</property>
<property name="proxool.xml">ProxoolConf.xml</property>
<property name="connection.provider_class">net.sf.hibernate.connection.ProxoolConnectionProvider</property>

然後,在和hibernate.cfg.xml同一個目錄下,加一個ProxoolConf.xml文件,內容為

<?xml version="1.0" encoding="utf-8"?>
<!-- the proxool configuration can be embedded within your own application's.
Anything outside the "proxool" tag is ignored. -->
<something-else-entirely>
<proxool>
<alias>pool1</alias>
<!--proxool只能管理由自己產生的連接-->
<driver-url>jdbc:mysql://localhost:3306/struts?useUnicode=true&characterEncoding=GBK</driver-url>
<driver-class>org.gjt.mm.mysql.Driver</driver-class>
<driver-properties>
<property name="user" value="root"/>
<property name="password" value="8888"/>
</driver-properties>
<!-- proxool自動偵察各個連接狀態的時間間隔(毫秒),偵察到空閑的連接就馬上回收,超時的銷毀-->
<house-keeping-sleep-time>90000</house-keeping-sleep-time>
<!-- 指因未有空閑連接可以分配而在隊列中等候的最大請求數,超過這個請求數的用戶連接就不會被接受-->
<maximum-new-connections>20</maximum-new-connections>
<!-- 最少保持的空閑連接數-->
<prototype-count>5</prototype-count>
<!-- 允許最大連接數,超過了這個連接,再有請求時,就排在隊列中等候,最大的等待請求數由maximum-new-connections決定-->
<maximum-connection-count>100</maximum-connection-count>
<!-- 最小連接數-->
<minimum-connection-count>10</minimum-connection-count>
</proxool>
</something-else-entirely>

並在classespath中加入proxool-0.8.3.jar

Ⅷ hibernate連接mysql資料庫,表都已經映射出來了,但是查詢出錯

你設個斷點debug調試下,看查詢出來的返回值有沒有值,如果是null,那說明你的查詢語句或者hibernate的配置文件有問題(多半是方言dialect配置有問題)。如果有值,那說明是你的獲取方法有問題了。

Ⅸ hibernate 配置里要連接資料庫,怎麼才能知道自己MySQL資料庫的url

String url = "jdbc:mysql://localhost/資料庫名;

這個url會在hibernate中的配置文件有寫,如果引進properties的話那麼就在 .properties文件中。

Ⅹ hibernate 怎麼連資料庫

首先,我們把hibernate最基本的資料庫連接,使用mysql。 見一個java工程,見一個包名為book, 在book的包下加一個java類Book.java,
其代碼如下: package book; public class Book { private Integer id; private String name; private String writer; public Integer get hibernate最基本的資料庫連接,使用mysql。 見一個java工程,見一個包名為「book」

然後在在book的包下加一個java類Book.java,其代碼如下: package book; public class Book { private Integer id; private String name; private String writer; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getWriter() { return writer; } public void setWriter(String writer) { this.writer = writer; } }

熱點內容
創建實例在linux 發布:2024-10-07 18:03:16 瀏覽:485
黑客學c語言 發布:2024-10-07 17:37:39 瀏覽:942
ftp比較文件 發布:2024-10-07 17:04:56 瀏覽:39
如何配置幼兒園園內的玩具 發布:2024-10-07 17:04:23 瀏覽:863
干支日演算法 發布:2024-10-07 16:47:17 瀏覽:502
sqlin語句用法 發布:2024-10-07 16:45:05 瀏覽:640
直出伺服器怎麼樣 發布:2024-10-07 15:41:36 瀏覽:479
比亞迪唐dmi哪個配置性價比 發布:2024-10-07 15:19:28 瀏覽:903
編譯器按變數 發布:2024-10-07 15:07:03 瀏覽:775
怎麼忘記電腦wifi密碼怎麼辦 發布:2024-10-07 15:02:18 瀏覽:426