hibernate查询案例

来源:互联网 发布:杭州行知小学是重点吗 编辑:程序博客网 时间:2024/06/11 13:10

示例bean类:

package com.bjsxt.bean;

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

@Entity
public class User {

 private int id;
 private String name;
 private String school;
 @Id
 @GeneratedValue(strategy=GenerationType.AUTO)
 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getSchool() {
  return school;
 }

 public void setSchool(String school) {
  this.school = school;
 }

}

工具类:

package com.bjsxt.utils;

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

public class HibUtils {

 private static SessionFactory factory;
 
 static {
  Configuration cfg = new AnnotationConfiguration().configure();
  factory = cfg.buildSessionFactory();
 }

 public static SessionFactory getSessionFactory() {
  return factory;

 }

 public static Session getSession() {
  return factory.openSession();

 }

 private HibUtils() {

 }
}

 

测试类:

package com.bjsxt.bean;

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

import com.bjsxt.utils.HibUtils;

public class UserTest {

 public static void main(String[] args) {

  Session session = null;
  Transaction ts = null;
  try {
   session = HibUtils.getSession();
   ts = session.beginTransaction();
   User u1 = new User();
   u1.setId(0);
   u1.setName("张三");
   u1.setSchool("清华大学");
   User u2 = new User();
   u2.setId(1);
   u2.setName("李四");
   u2.setSchool("北京大学");
   User u3 = new User();
   u3.setId(2);
   u3.setName("王五");
   u3.setSchool("南京大学");
   session.save(u1);
   session.save(u2);
   session.save(u3);
   ts.commit();
  } catch (Exception e) {
   // TODO: handle exception
  }finally{
   if (session!=null) {
    session.close();
   }
  }
 }
}

hibernate查询类:

package com.bjsxt.bean;

import java.util.List;

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

import com.bjsxt.utils.HibUtils;

public class FromUser {
 public static void main(String[] args) {

  Session session = null;
  Transaction ts = null;
  try {
   session = HibUtils.getSession();
   ts = session.beginTransaction();
   String hql = "from com.bjsxt.bean.User";
   Query q = session.createQuery(hql);
   List<User> l = q.list();
   for (int x = 0; x < l.size(); x++) {
    User u = l.get(x);
    System.out.println(u.getId() + "-" + u.getName() + "-"
      + u.getSchool());
   }
   ts.commit();
  } catch (Exception e) {
   // TODO: handle exception
  } finally {
   if (session != null) {
    session.close();
   }
  }

 }
}

配置文件hibernate.cfg.xml

<!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="format_sql">true</property>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hb</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.connection.password">1</property>
  <property name="hibernate.hbm2ddl.auto">update</property>
  <mapping class="com.bjsxt.bean.User"/>
  
 </session-factory>
</hibernate-configuration>

 

log4j.properties

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=warn, stdout

#log4j.logger.org.hibernate=info
log4j.logger.org.hibernate=debug

### log HQL query parser activity
#log4j.logger.org.hibernate.hql.ast.AST=debug

### log just the SQL
#log4j.logger.org.hibernate.SQL=debug

### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=debug
#log4j.logger.org.hibernate.type=debug

### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=debug

### log HQL parse trees
#log4j.logger.org.hibernate.hql=debug

### log cache activity ###
#log4j.logger.org.hibernate.cache=debug

### log transaction activity
#log4j.logger.org.hibernate.transaction=debug

### log JDBC resource acquisition
#log4j.logger.org.hibernate.jdbc=debug

### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace