hibernate单独使用参考示例

Posted suheng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hibernate单独使用参考示例相关的知识,希望对你有一定的参考价值。

库配置

<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>4.3.8.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.46</version>
</dependency>

hibernate配置

hibernate.cfg.xml

技术分享图片
<?xml version="1.0" encoding="GBK"?>
<!-- 指定Hibernate配置文件的DTD信息 -->  
<!DOCTYPE hibernate-configuration PUBLIC  
<span style="white-space:pre;">
</span>
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
<span style="white-space:pre;">
</span>
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- hibernate-configuration是配置文件的根元素 -->
<hibernate-configuration>
   <session-factory>
      <!-- 指定连接数据库所用的驱动 -->
      <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
      <!-- 指定连接数据库的url,其中hibernate是本应用连接的数据库名 -->
      <property name="connection.url">jdbc:mysql://localhost/hibernate</property>
      <!-- 指定连接数据库的用户名 -->
      <property name="connection.username">test</property>
      <!-- 指定连接数据库的密码 -->
      <property name="connection.password">******</property>
      <!-- 指定连接池里最大连接数 -->
      <property name="hibernate.c3p0.max_size">20</property>
      <!-- 指定连接池里最小连接数 -->
      <property name="hibernate.c3p0.min_size">1</property>
      <!-- 指定连接池里连接的超时时长 -->
      <property name="hibernate.c3p0.timeout">5000</property>
      <!-- 指定连接池里最大缓存多少个Statement对象 -->
      <property name="hibernate.c3p0.max_statements">100</property>
      <property name="hibernate.c3p0.idle_test_period">3000</property>
      <property name="hibernate.c3p0.acquire_increment">2</property>
      <property name="hibernate.c3p0.validate">true</property>
      <!-- 指定数据库方言 -->
      <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
      <!-- 根据需要自动创建数据库 -->
      <property name="hbm2ddl.auto">update</property>
      <!-- 显示Hibernate持久化操作所生成的SQL -->
      <property name="show_sql">true</property>
      <!-- 将SQL脚本进行格式化后再输出 -->
      <property name="hibernate.format_sql">true</property>
      <!-- 罗列所有持久化类的类名 -->
      <mapping class="hibernate.test.EntityA" />
      <mapping class="hibernate.test.EntityB" />
   </session-factory>
</hibernate-configuration>
View Code

获得session的工具类

技术分享图片
public class HibernateUtil {
    public static final SessionFactory sessionFactory;

    static {
        try {
            // 使用默认的hibernate.cfg.xml配置文件创建Configuration实例
            Configuration cfg = new Configuration().configure();
            // 以Configuration实例来创建SessionFactory实例
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties())
                    .build();
            sessionFactory = cfg.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    // ThreadLocal可以隔离多个线程的数据共享,因此不再需要对线程同步
    public static final ThreadLocal<Session> session = new ThreadLocal<Session>();

    public static Session currentSession() throws HibernateException {
        Session s = session.get();
        // 如果该线程还没有Session,则创建一个新的Session
        if (s == null) {
            s = sessionFactory.openSession();
            // 将获得的Session变量存储在ThreadLocal变量session里
            session.set(s);
        }
        return s;
    }

    public static void closeSession() throws HibernateException {
        Session s = session.get();
        if (s != null) {
            s.close();
        }
        session.set(null);
    }
}
View Code

实体类

技术分享图片
package hibernate.test;  
  
  
import java.io.Serializable;  
import java.util.HashSet;  
import java.util.Set;  
  
  
import javax.persistence.Entity;  
import javax.persistence.GeneratedValue;  
import javax.persistence.GenerationType;  
import javax.persistence.Id;  
import javax.persistence.OneToMany;  
  
  
@Entity  
public class EntityA implements Serializable {  
    @Id  
    @GeneratedValue(strategy = GenerationType.AUTO)  
    private Integer ida;  
    private String columnOne;  
    private String columnTwo;  
  
  
    @OneToMany(targetEntity = EntityB.class, mappedBy = "ea")  
    private Set<EntityB> ebs = new HashSet<EntityB>();  
  
  
    public EntityA() {  
  
  
    }  
  
  
    public EntityA(String columnOne, String columnTwo) {  
        this.columnOne = columnOne;  
        this.columnTwo = columnTwo;  
    }  
  
  
    public Integer getIda() {  
        return ida;  
    }  
  
  
    public void setIda(Integer ida) {  
        this.ida = ida;  
    }  
  
  
    public String getColumnOne() {  
        return columnOne;  
    }  
  
  
    public void setColumnOne(String columnOne) {  
        this.columnOne = columnOne;  
    }  
  
  
    public String getColumnTwo() {  
        return columnTwo;  
    }  
  
  
    public void setColumnTwo(String columnTwo) {  
        this.columnTwo = columnTwo;  
    }  
  
  
    public Set<EntityB> getEbs() {  
        return ebs;  
    }  
  
  
    public void setEbs(Set<EntityB> ebs) {  
        this.ebs = ebs;  
    }  
  
  
}  
View Code
技术分享图片
package hibernate.test;  
  
  
import java.io.Serializable;  
  
  
import javax.persistence.Entity;  
import javax.persistence.GeneratedValue;  
import javax.persistence.GenerationType;  
import javax.persistence.Id;  
import javax.persistence.JoinColumn;  
import javax.persistence.ManyToOne;  
  
  
@Entity  
public class EntityB implements Serializable {  
    @Id  
    @GeneratedValue(strategy = GenerationType.AUTO)  
    private Integer idb;  
    private String columnOne;  
    private String columnTwo;  
    @ManyToOne(targetEntity = EntityA.class)  
    @JoinColumn(name = "b_a", nullable = false)  
    private EntityA ea;  
  
  
    public EntityB() {  
  
  
    }  
  
  
    public EntityB(String columnOne, String columnTwo) {  
        this.columnOne = columnOne;  
        this.columnTwo = columnTwo;  
    }  
  
  
    public Integer getIdb() {  
        return idb;  
    }  
  
  
    public void setIdb(Integer idb) {  
        this.idb = idb;  
    }  
  
  
    public String getColumnOne() {  
        return columnOne;  
    }  
  
  
    public void setColumnOne(String columnOne) {  
        this.columnOne = columnOne;  
    }  
  
  
    public String getColumnTwo() {  
        return columnTwo;  
    }  
  
  
    public void setColumnTwo(String columnTwo) {  
        this.columnTwo = columnTwo;  
    }  
  
  
    public EntityA getEa() {  
        return ea;  
    }  
  
  
    public void setEa(EntityA ea) {  
        this.ea = ea;  
    }  
  
  
}  
View Code

测试

package test;  
  
import org.hibernate.Session;  
import org.hibernate.Transaction;  
  
import hibernate.test.EntityA;  
import util.HibernateUtil;  
  
public class Main {  
    public static void main(String[] args) {  
        Session session = HibernateUtil.currentSession();  
        EntityA a1 = new EntityA("cOne_r1", "cTwo_r1");  
        Transaction t = session.getTransaction();  
        t.begin();  
        session.save(a1);  
        t.commit();  
        HibernateUtil.closeSession();  
    }  
}  

 

以上是关于hibernate单独使用参考示例的主要内容,如果未能解决你的问题,请参考以下文章

具有运行时 pojos 的带有 Hibernate 的 OSGi 片段包

LockSupport.java 中的 FIFO 互斥代码片段

带有片段的两个面板 UI 与单独的活动

Android tv:标题片段中每个项目的 Webview

Android 片段和活动

Android课程---Android Studio使用小技巧:提取方法代码片段