如何使用hibernate访问数据库

如何使用hibernate访问数据库,第1张

首先,我们把hibernate最基本的数据库连接,使用mysql。 见一个java工程,见一个包名为book, 在book的包下加一个java类Book.java,其代码如下: package bookpublic class Book { private Integer idprivate String nameprivate String writerpublic 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的jar包 到WEB-INF的lib下

第二步:在src目录下写一个hibernate.cfg.xml配置文件

<?xml version='1.0' encoding='gb2312'?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<!--显示执行的SQL语句-->

<property name="show_sql">true</property>

<!--连接字符串-->

<property name="connection.url">jdbc:oracle:thin:@localhost:1521:ORCL</property>

<!--连接数据库的用户名-->

<property name="connection.username">bsp</property>

<!--数据库用户密码-->

<property name="connection.password">bsp</property>

<!--数据库驱动-->

<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>

<!--JDBC连接池(使用内置的连接池)-->

<property name="connection.pool_size">1</property>

<!--设置Hibernate自动管理上下文的策略-->

<property name="current_session_context_class">thread</property>

<!--选择使用的方言-->

<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>

<!--在启动时删除并重新创建数据库-->

<property name="hbm2ddl.auto">update</property>

<mapping class="com.entity.Person"></mapping>

</session-factory>

</hibernate-configuration>

第三步:在src目录下建一个com.entity包,里面建一个Person类

package com.bsp.entity

import javax.persistence.Column

import javax.persistence.Entity

import javax.persistence.Id

@Entity

public class Person {

private String id

private String name

@Id

@Column(length=10)

public String getId() {

return id

}

public void setId(String id) {

this.id = id

}

@Column(length=10)

public String getName() {

return name

}

public void setName(String name) {

this.name = name

}

}

第四步:建一个测试类

package com.bsp.test

import org.hibernate.Session

import com.HibernateSessionFactory

import junit.framework.TestCase

public class TestBsp extends TestCase{

public void testSave() throws Exception {

Session session = HibernateSessionFactory.getSession()

session.close()

}

}

运行就可以自动在数据库里生成表了

Hibernate查询所有数据的 *** 作方式有三种。

1、Query

(1)使用该方法查询时,不需要编写sql语句,但是需要编写hql(Hibernate Query Language)语句,该语句是Hibernate查询语言。

(2)hql语言 *** 作的是实体类和实体类的属性,比如查询所有数据的hql语句为:from 实体类名称。

(3)使用方法:首先创建Query对象,然后调用该对象的List方法返回数据集合。

@Test

public void test11(){

SessionFactory sessionFactory = null

Session session = null

Transaction tx = null

try {

sessionFactory = HibernateUtils.getFactory()

session = sessionFactory.getCurrentSession()

tx = session.beginTransaction()

/**

* 使用session对象的createQuery方法创建Query对象。

* 参数为hql语句

* 使用QUERY对象的list方法获取数据集合

*/

Query query =session.createQuery("from UserEntity")

List<UserEntity>list = query.list()

//使用forEach遍历集合

for (UserEntity userEntity : list) {

System.out.println(userEntity)

}

tx.commit()

} catch (Exception e) {

tx.rollback()

}finally{

sessionFactory.close()

}

}

2、criteria

(1)使用该对象不需要写hql语句,只需要指定实体类。

(2)使用方法:首先创建criteria对象,然后调用list返回数据集合。

@Test

public void test12(){

SessionFactory sessionFactory = null

Session session = null

Transaction tx = null

try {

sessionFactory = HibernateUtils.getFactory()

session = sessionFactory.getCurrentSession()

tx = session.beginTransaction()

/**

* 使用session对象的createCriteria方法创建criteria对象。

* 使用criteria对象的list方法获取数据集合

*/

Criteria criteria =session.createCriteria(UserEntity.class)

List<UserEntity>list = criteria.list()

//使用forEach遍历集合

for (UserEntity userEntity : list) {

System.out.println(userEntity)

}

tx.commit()

} catch (Exception e) {

tx.rollback()

}finally{

sessionFactory.close()

}

}

3、SQLQuery

(1)使用该对象,需要写底层的SQL语句。

(2)实现方法:首先创建该对象,然后调用list。

@Test

public void test13(){

SessionFactory sessionFactory = null

Session session = null

Transaction tx = null

try {

sessionFactory = HibernateUtils.getFactory()

session = sessionFactory.getCurrentSession()

tx = session.beginTransaction()

/**

* 使用session对象的createSQLQuery方法创建SQLQuery对象。

* 使用qQLQuery对象的list方法获取数据集合,集合里面不是对象,而是数组

*/

SQLQuery qQLQuery =session.createSQLQuery("select * from t_user")

List<Object[]>list = qQLQuery.list()

//使用forEach遍历集合

for (Object[] objects : list) {

System.out.println(Arrays.toString(objects))

}

tx.commit()

} catch (Exception e) {

tx.rollback()

}finally{

sessionFactory.close()

}

}

(3)数组转换成对象

@Test

public void test13(){

SessionFactory sessionFactory = null

Session session = null

Transaction tx = null

try {

sessionFactory = HibernateUtils.getFactory()

session = sessionFactory.getCurrentSession()

tx = session.beginTransaction()

/**

* 使用session对象的createSQLQuery方法创建SQLQuery对象。

* 使用qQLQuery对象的list方法获取数据集合,集合里面不是对象,而是数组

*/

SQLQuery qQLQuery =session.createSQLQuery("select * from t_user")

//将数组装载进实体中

qQLQuery.addEntity(UserEntity.class)

List<UserEntity >list = qQLQuery.list()

//使用forEach遍历集合

for (UserEntity userEntity : list) {

System.out.println(userEntity)

}

tx.commit()

} catch (Exception e) {

tx.rollback()

}finally{

sessionFactory.close()

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/sjk/9925926.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-03
下一篇 2023-05-03

发表评论

登录后才能评论

评论列表(0条)

保存