您的位置:首页 > 其它

Hibernate 的 Criteria用法,完整的一个例子

2017-10-17 18:01 561 查看
数据库:

/*
MySQL Data Transfer
Source Host: localhost
Source Database: test
Target Host: localhost
Target Database: test
Date: 2011-10-18 16:44:27
*/

SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for table_a
-- ----------------------------
DROP TABLE IF EXISTS `table_a`;
CREATE TABLE `table_a` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(20) default NULL,
PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for table_b
-- ----------------------------
DROP TABLE IF EXISTS `table_b`;
CREATE TABLE `table_b` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(20) default NULL,
`aid` int(11) default NULL,
PRIMARY KEY  (`id`),
KEY `FK_aid_A_id` (`aid`),
CONSTRAINT `FK_aid_A_id` FOREIGN KEY (`aid`) REFERENCES `table_a` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for table_c
-- ----------------------------
DROP TABLE IF EXISTS `table_c`;
CREATE TABLE `table_c` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(20) default NULL,
`bid` int(11) default NULL,
PRIMARY KEY  (`id`),
KEY `FK_bid_B_id` (`bid`),
CONSTRAINT `FK_bid_B_id` FOREIGN KEY (`bid`) REFERENCES `table_b` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records
-- ----------------------------
INSERT INTO `table_a` VALUES ('1', 'a_1');
INSERT INTO `table_a` VALUES ('2', 'a_2');
INSERT INTO `table_a` VALUES ('3', 'a_3');
INSERT INTO `table_a` VALUES ('4', 'a_4');
INSERT INTO `table_a` VALUES ('5', 'a_5');
INSERT INTO `table_a` VALUES ('6', 'a_6');
INSERT INTO `table_a` VALUES ('7', 'a_7');
INSERT INTO `table_a` VALUES ('8', 'a_8');
INSERT INTO `table_a` VALUES ('9', 'a_9');
INSERT INTO `table_a` VALUES ('10', 'a_10');
INSERT INTO `table_b` VALUES ('1', 'b_1', '1');
INSERT INTO `table_b` VALUES ('2', 'b_2', '1');
INSERT INTO `table_b` VALUES ('3', 'b_3', '1');
INSERT INTO `table_b` VALUES ('4', 'b_4', '1');
INSERT INTO `table_b` VALUES ('5', 'b_5', '1');
INSERT INTO `table_b` VALUES ('6', 'b_6', '1');
INSERT INTO `table_b` VALUES ('7', 'b_7', '1');
INSERT INTO `table_b` VALUES ('8', 'b_8', '1');
INSERT INTO `table_b` VALUES ('9', 'b_9', '1');
INSERT INTO `table_b` VALUES ('10', 'b_10', '1');
INSERT INTO `table_c` VALUES ('1', 'c_1', '1');
INSERT INTO `table_c` VALUES ('2', 'c_2', '1');
INSERT INTO `table_c` VALUES ('3', 'c_3', '1');
INSERT INTO `table_c` VALUES ('4', 'c_4', '1');
INSERT INTO `table_c` VALUES ('5', 'c_5', '1');
INSERT INTO `table_c` VALUES ('6', 'c_6', '1');
INSERT INTO `table_c` VALUES ('7', 'c_7', '1');
INSERT INTO `table_c` VALUES ('8', 'c_8', '1');
INSERT INTO `table_c` VALUES ('9', 'c_9', '1');
INSERT INTO `table_c` VALUES ('10', 'c_10', '1');

 
表映射的3个类

package com.hibernate.entity;

import java.util.HashSet;

/**
* TableA entity. @author MyEclipse Persistence Tools
*/
@Entity
@Table(name = "table_a", catalog = "test")
public class TableA implements java.io.Serializable {

// Fields

/**
*
*/
private static final long serialVersionUID = 5391348233326253804L;
private Integer id;
private String name;
private Set<TableB> tableBs = new HashSet<TableB>(0);

// Constructors

/** default constructor */
public TableA() {
}

/** full constructor */
public TableA(String name, Set<TableB> tableBs) {
this.name = name;
this.tableBs = tableBs;
}

// Property accessors
@Id
@GeneratedValue
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}

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

@Column(name = "name", length = 20)
public String getName() {
return this.name;
}

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

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "tableA")
public Set<TableB> getTableBs() {
return this.tableBs;
}

public void setTableBs(Set<TableB> tableBs) {
this.tableBs = tableBs;
}

}

package com.hibernate.entity;

import java.util.HashSet;

/**
* TableB entity. @author MyEclipse Persistence Tools
*/
@Entity
@Table(name = "table_b", catalog = "test")
public class TableB implements java.io.Serializable {

// Fields

/**
*
*/
private static final long serialVersionUID = -4305123492413110511L;
private Integer id;
private TableA tableA;
private String name;
private Set<TableC> tableCs = new HashSet<TableC>(0);

// Constructors

/** default constructor */
public TableB() {
}

/** full constructor */
public TableB(TableA tableA, String name, Set<TableC> tableCs) {
this.tableA = tableA;
this.name = name;
this.tableCs = tableCs;
}

// Property accessors
@Id
@GeneratedValue
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}

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

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "aid")
public TableA getTableA() {
return this.tableA;
}

public void setTableA(TableA tableA) {
this.tableA = tableA;
}

@Column(name = "name", length = 20)
public String getName() {
return this.name;
}

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

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "tableB")
public Set<TableC> getTableCs() {
return this.tableCs;
}

public void setTableCs(Set<TableC> tableCs) {
this.tableCs = tableCs;
}

}

package com.hibernate.entity;

import javax.persistence.Column;

/**
* TableC entity. @author MyEclipse Persistence Tools
*/
@Entity
@Table(name = "table_c", catalog = "test")
public class TableC implements java.io.Serializable {

// Fields

/**
*
*/
private static final long serialVersionUID = -8806809289431187808L;
private Integer id;
private TableB tableB;
private String name;

// Constructors

/** default constructor */
public TableC() {
}

/** full constructor */
public TableC(TableB tableB, String name) {
this.tableB = tableB;
this.name = name;
}

// Property accessors
@Id
@GeneratedValue
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}

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

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "bid")
public TableB getTableB() {
return this.tableB;
}

public void setTableB(TableB tableB) {
this.tableB = tableB;
}

@Column(name = "name", length = 20)
public String getName() {
return this.name;
}

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

}

 
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">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.url">
jdbc:mysql://localhost/test
</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>

<!-- Disable the second-level cache  -->
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<property name="format_sql">true</property>
<!--
<mapping class="com.hibernate.entity.Husband" />
<mapping class="com.hibernate.entity.Wife" />
===================================================
<mapping class="com.hibernate.entity.Teacher" />
<mapping class="com.hibernate.entity.Student" />
<mapping class="com.hibernate.entity.Tgroup" />
<mapping class="com.hibernate.entity.Tuser" />
-->

<mapping class="com.hibernate.entity.TableC" />
<mapping class="com.hibernate.entity.TableB" />
<mapping class="com.hibernate.entity.TableA" />
</session-factory>

</hibernate-configuration>

 
log4j.properties

### set log levels ###
log4j.rootLogger=warn, stdout, D, E

### 输出到控制台 ###
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:%L - %m%n

### 输出到日志文件 ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ${WORKDIR}/logs/log.log
log4j.appender.D.Append = true
## 输出DEBUG级别以上的日志
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [%t:%r] - %c:%L - [%p] %m%n

### 保存异常信息到单独文件 ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
## 异常日志文件名
log4j.appender.E.File = ${WORKDIR}/logs/error.log
log4j.appender.E.Append = true
## 只输出ERROR级别以上的日志!!!
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern =%-d{yyyy-MM-dd HH\:mm\:ss} [%t\:%r] - %c\:%L - [%p] %m%n

 
测试代码:

 

package com.hibernate.test;

import java.util.HashMap;

public class ORMappingTest {

private static SessionFactory sessionFactory;

@BeforeClass
public static void setUpBeforeClass() throws Exception {
//new SchemaExport(new AnnotationConfiguration().configure()).create(true, true);
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}

@AfterClass
public static void tearDownAfterClass() throws Exception {
sessionFactory.close();
}

//根据annotation生成表,当然,这里并不使用到
@Test
public void testSchemaExport() {
new SchemaExport(new AnnotationConfiguration().configure()).create(true, true);
}

//把值存入A B C三张表
@Test
public void saveABC() {
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
TableA a = null;
for (int i = 0; i < 10; i++) {
a = new TableA();
a.setName("a_" + (i + 1));
s.save(a);
}
a = (TableA)s.get(TableA.class, 1);
TableB b = null;
for (int i = 0; i < 10; i++) {
b = new TableB();
b.setName("b_" + (i + 1));
b.setTableA(a);
s.save(b);
}
TableC c = null;
b = (TableB)s.get(TableB.class, 1);
for (int i = 0; i < 10; i++) {
c = new TableC();
c.setName("c_" + (i + 1));
c.setTableB(b);
s.save(c);
}
s.getTransaction().commit();
}

@Test
public void testQBC() {
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
Integer []id_s = {1,2,3,4};
Criteria c = s.createCriteria(TableA.class)// 这里相当于 from TableA
.add(Restrictions.in("id", id_s)) //这里取id在1,2,3,4中的TableA
.createCriteria("tableBs") //表示把tableBs加进去再作为一个查询条件,tableBs是A对象中的一个属性
.add(Restrictions.between("id", 5, 8))
;
List<TableA> taList = c.list();
for (TableA a : taList) {
System.out.println(a.getName());
}
}

}

 
 

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: