新建Java Project:testHibernate
在项目上右击AddHibernate Capabilities…
添加相关类及文件:
User.java/User.hbm.xml/Test.java
将User.hbm.xml文件添加到hibernate.cfg.xml文件中
主要代码如下:
Organ.java
package com.test.cn.entity;
import java.util.Set;
public class Organ {
private static final long serialVersionUID = 1602693228146040607L;
private long id;
private String organ;
private long idParent;
private String idSeq;
private String organCode;
private String sourceKey;
private String organLeader;
private String companyCode;
private Set users;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getOrgan() {
return organ;
}
public void setOrgan(String organ) {
this.organ = organ;
}
public long getIdParent() {
return idParent;
}
public void setIdParent(long idParent) {
this.idParent = idParent;
}
public String getIdSeq() {
return idSeq;
}
public void setIdSeq(String idSeq) {
this.idSeq = idSeq;
}
public String getOrganCode() {
return organCode;
}
public void setOrganCode(String organCode) {
this.organCode = organCode;
}
public String getOrganLeader() {
return organLeader;
}
public void setOrganLeader(String organLeader) {
this.organLeader = organLeader;
}
public String getSourceKey() {
return sourceKey;
}
public void setSourceKey(String sourceKey) {
this.sourceKey = sourceKey;
}
public String getCompanyCode() {
return companyCode;
}
public void setCompanyCode(String companyCode) {
this.companyCode = companyCode;
}
public Set getUsers() {
return users;
}
public void setUsers(Set users) {
this.users = users;
}
}
User.java
package com.test.cn.entity;
public class User {
private Integer id;
private String name;
private String password;
private String email;
private Integer organId;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getOrganId() {
return organId;
}
public void setOrganId(Integer organId) {
this.organId = organId;
}
}
配置文件如下:
Organ.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class
name="com.test.cn.entity.Organ"
table="tb_organ"
lazy="false"
>
<id
name="id"
column="id"
type="long"
>
<generator class="increment">
</generator>
</id>
<property
name="organ"
type="java.lang.String"
update="true"
insert="true"
column="organ"
length="254"
not-null="true"
/>
<property
name="idParent"
type="long"
update="true"
insert="true"
column="id_parent"
not-null="true"
/>
<property
name="idSeq"
type="java.lang.String"
update="true"
insert="true"
column="id_seq"
length="100"
not-null="false"
/>
<property
name="organCode"
type="java.lang.String"
update="true"
insert="true"
column="organCode"
length="50"
not-null="false"
/>
<property
name="sourceKey"
type="java.lang.String"
update="true"
insert="true"
column="sourceKey"
length="50"
not-null="false"
/>
<property
name="organLeader"
type="java.lang.String"
update="true"
insert="true"
column="organLeader"
length="20"
not-null="false"
/>
<property
name="companyCode"
type="java.lang.String"
update="true"
insert="true"
column="companyCode"
length="50"
not-null="false"
/>
<set name="users" table="tb_user" inverse="false" cascade="all" sort="unsorted">
<key column="organId"/>
<one-to-many class="com.test.cn.entity.User"/>
</set>
</class>
</hibernate-mapping>
User.hbm.xml
<?xml version="1.0" encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.test.cn.entity.User" table="tb_user">
<id name="id" column="id" type="java.lang.Integer">
<generator class="native"/>
</id>
<property name="name" column="name" type="java.lang.String"/>
<property name="password" column="password" type="java.lang.String"/>
<property name="email" column="email" type="java.lang.String"/>
</class>
<!-- 命名查询:定义查询条件 -->
<query name="getUserById">
<![CDATA[from User where id=:id]]>
</query>
</hibernate-mapping>
测试类:
TestOrgan.java
package com.test.cn.test;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.test.cn.HibernateSessionFactory;
import com.test.cn.entity.Organ;
import com.test.cn.entity.User;
public class TestOrgan {
public static void main(String[] args) {
System.out.println("--------begin---------");
getOrganByParentId(1l);
// getOrganById(2l);
System.out.println("--------OK!---------");
}
private static void getOrganByParentId(Long parentId) {
Configuration configuration = HibernateSessionFactory.getConfiguration().configure();
SessionFactory factory = configuration.buildSessionFactory();
Session session = factory.openSession();
Query query = session.createQuery("from Organ where idParent = " + parentId + " order by id ");
List<Organ> list = query.list();
for(Organ organ : list){
System.out.println(organ.getId() + "|" + organ.getOrgan() + "|" + organ.getIdParent() + "|" + organ.getIdSeq());
Iterator it = organ.getUsers().iterator();
while(it.hasNext()){
User user = (User)it.next();
System.out.println(user.getId() + "|" + user.getName() + "|" + user.getPassword() + "|" + user.getEmail());
}
}
}
private static void getOrganById(Long id) {
Configuration configuration = HibernateSessionFactory.getConfiguration().configure();
SessionFactory factory = configuration.buildSessionFactory();
Session session = factory.openSession();
Organ organ = (Organ)session.load(Organ.class, id);
System.out.println(organ.getId() + "|" + organ.getOrgan() + "|" + organ.getIdParent() + "|" + organ.getIdSeq());
Iterator it = organ.getUsers().iterator();
while(it.hasNext()){
User user = (User)it.next();
System.out.println(user.getId() + "|" + user.getName() + "|" + user.getPassword() + "|" + user.getEmail());
}
}
}
MyEclipse自动帮助生成的文件:HibernateSessionFactory.java
package com.test.cn;
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 = "/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;
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;
}
}
MyEclipse自动帮助生成的文件:hibernate.cfg.xml。需要添加<mapping/>映射
<?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="connection.url">
jdbc:oracle:thin:@127.0.0.1:1521:orcl
</property>
<property name="connection.username">test</property>
<property name="connection.password">test</property>
<property name="dialect">
org.hibernate.dialect.Oracle9Dialect
</property>
<property name="myeclipse.connection.profile">oracle</property>
<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping resource="com/test/cn/entity/User.hbm.xml" />
<mapping resource="com/test/cn/entity/Organ.hbm.xml" />
</session-factory>
</hibernate-configuration>