时间长了对hibernate的基础使用有点生疏,于是决定重新温习一下。
一.登录hibernate官方,下载hibernate相关jar包。
将下载的压缩包解压:在该hibernate-release-4.2.20.Final\lib\required 路径下的找到hibernate所需要的jar包,将该目录下所有jar包加入工程。
二.hibernate配置文件。
配置文件可以在快速开始文档的工程里找到 参考路径:hibernate-release-4.2.20.Final\documentation\quickstart\en-US\html\files,在该文件下有一个压缩包,将其解压,可以看到示例工程,随便一个工程都能找到配置文件
下面是basic工程的配置文件
<?xml version='1.0' encoding='utf-8'?> <!-- ~ Hibernate, Relational Persistence for Idiomatic Java ~ ~ Copyright (c) 2010, Red Hat Inc. or third-party contributors as ~ indicated by the @author tags or express copyright attribution ~ statements applied by the authors. All third-party contributions are ~ distributed under license by Red Hat Inc. ~ ~ This copyrighted material is made available to anyone wishing to use, modify, ~ copy, or redistribute it subject to the terms and conditions of the GNU ~ Lesser General Public License, as published by the Free Software Foundation. ~ ~ This program is distributed in the hope that it will be useful, ~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY ~ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License ~ for more details. ~ ~ You should have received a copy of the GNU Lesser General Public License ~ along with this distribution; if not, write to: ~ Free Software Foundation, Inc. ~ 51 Franklin Street, Fifth Floor ~ Boston, MA 02110-1301 USA --> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">org.h2.Driver</property> <property name="connection.url">jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE</property> <property name="connection.username">sa</property> <property name="connection.password"/> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.H2Dialect</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">create</property> <mapping resource="org/hibernate/tutorial/hbm/Event.hbm.xml"/> </session-factory> </hibernate-configuration>
找到对应位置,更换自己的数据库就好了。
三.创建测试用例。
Student类:
package com.daxingzsh.po;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "STUDENT")
public class Student {
private String sId;
private String sName;
private String sSex;
private Classes classes;
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
@Column(name = "S_ID")
public String getsId() {
return sId;
}
public void setsId(String sId) {
this.sId = sId;
}
@Column(name = "S_NAME")
public String getsName() {
return sName;
}
public void setsName(String sName) {
this.sName = sName;
}
@Column(name = "S_SEX")
public String getsSex() {
return sSex;
}
public void setsSex(String sSex) {
this.sSex = sSex;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "CLASS_ID")
public Classes getClasses() {
return classes;
}
public void setClasses(Classes classes) {
this.classes = classes;
}
@Override
public String toString() {
return "Student [sId=" + sId + ", sName=" + sName + ", sSex=" + sSex
+ ", classes=" + classes + "]";
}
}
Classes类:
package com.daxingzsh.po;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "CLASSES_TABLE")
public class Classes {
private String classId;
private String className;
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
@Column(name = "CLASS_ID")
public String getClassId() {
return classId;
}
public void setClassId(String classId) {
this.classId = classId;
}
@Column(name = "CLASS_NAME")
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
Student与Classes为N-1(多对一)关系。由于在配置文件中配置了
<property name="hbm2ddl.auto">create</property>
属性,这里hibernate将自动创建数据库表(如果已存在表,则会被删除)。
更改hibernate配置文件,添加mapping映射
<mapping class="com.daxingzsh.po.Student"/> <mapping class="com.daxingzsh.po.Classes"/>
四.测试代码:
package com.daxingzsh.test;
import java.util.List;
import junit.framework.TestCase;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;
import com.daxingzsh.po.Classes;
import com.daxingzsh.po.Student;
public class MyTest extends TestCase{
private SessionFactory sessionFactory;
private Session session;
@Override
protected void setUp() throws Exception {
System.out.println("init ...");
sessionFactory = new Configuration().configure().buildSessionFactory();
}
@Override
protected void tearDown() throws Exception {
if(sessionFactory != null)
sessionFactory.close();
}
@Test
public void testSearch(){
test();
session = sessionFactory.openSession();
session.beginTransaction();
Criteria cri = session.createCriteria(Student.class);
cri.createAlias("classes", "c1");
cri.add(Restrictions.eq("c1.className", "class1"));
List<Student> list = cri.list();
for(Student st : list){
System.out.println(st.toString());
}
// Criteria cri2 = cri.createCriteria("classes");
// cri2.add(Restrictions.eq("className", "class1"));
// List<Student> list1 = cri2.list();
// for(Student st : list1){
// System.out.println(st.toString());
// }
session.getTransaction().commit();
session.close();
}
// @Test
public void test() {
System.out.println("start.....");
session = sessionFactory.openSession();
session.beginTransaction();
Student s = new Student();
s.setsName("daxin"); s.setsSex("男");
Classes classes = new Classes();
classes.setClassName("class1");
s.setClasses(classes);
session.save(classes);
session.save(s);
session.getTransaction().commit();
session.close();
System.out.println("end ....");
}
}
经过测试则表明hibernate已经配置好了。
特别说明:hibernate的最新版本已经更新到5.0。