当前位置:首页 » 操作系统 » 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; } }

热点内容
直出服务器怎么样 发布:2024-10-07 15:41:36 浏览:476
比亚迪唐dmi哪个配置性价比 发布:2024-10-07 15:19:28 浏览:901
编译器按变量 发布:2024-10-07 15:07:03 浏览:773
怎么忘记电脑wifi密码怎么办 发布:2024-10-07 15:02:18 浏览:424
安卓开发java开发 发布:2024-10-07 15:01:29 浏览:94
工业级安卓主板价格怎么样 发布:2024-10-07 14:07:57 浏览:626
编程先乘除 发布:2024-10-07 13:58:45 浏览:269
编译内核时发生循环编译 发布:2024-10-07 13:58:43 浏览:495
当下笔记本电脑什么配置好 发布:2024-10-07 12:57:33 浏览:471
安卓倒车轨迹怎么调 发布:2024-10-07 12:54:47 浏览:916