compass 与hibernate 的集成,做到数据库的数据通过 hibernate 更新后,很快反应到compass 的索引中去

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="connection.username">root</property>
    <property name="connection.password">root</property>
    <property name="connection.url">
        jdbc:mysql://localhost:3306/test
    </property>
    <property name="dialect">
        org.hibernate.dialect.MySQLDialect
    </property>

    <property name="connection.driver_class">
        com.mysql.jdbc.Driver
    </property>

索引 的存放位置
    <property name="compass.engine.connection">target/index</property>

    <property name="hibernate.show_sql">true</property>
    <property name="format_sql">true</property>
 
        <property name="hbm2ddl.auto">update</property>
 

    <mapping class="org.jixiuf.pojo.Role" />
 
    <mapping class="org.jixiuf.pojo.User" />
    几个监听器,
      <event type="post-update">
      <listener class="org.compass.gps.device.hibernate.embedded.CompassEventListener"/>
  </event>
  <event type="post-insert">
      <listener class="org.compass.gps.device.hibernate.embedded.CompassEventListener"   />
  </event>
  <event type="post-delete">
      <listener class="org.compass.gps.device.hibernate.embedded.CompassEventListener"/>
  </event>
  <event type="post-collection-recreate">
      <listener class="org.compass.gps.device.hibernate.embedded.CompassEventListener"/>
  </event>
  <event type="post-collection-remove">
      <listener class="org.compass.gps.device.hibernate.embedded.CompassEventListener"/>
  </event>
  <event type="post-collection-update">
      <listener class="org.compass.gps.device.hibernate.embedded.CompassEventListener"/>
  </event>

   
</session-factory>

</hibernate-configuration>

 

 

============================

另外可以有compass.hibernate.config 这个属性,指向compass.cfg.xml 的位置

 

另外只需在pojo ,bean 中加入annotation ,如@Searchable @SearchableId 等

在向数据库中添加数据的时候 ,也会在compass 中的索引目录中存储相应数据

 

 

======================================================

package org.jixiuf.pojo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

import org.compass.annotations.Index;
import org.compass.annotations.Searchable;
import org.compass.annotations.SearchableId;
import org.compass.annotations.SearchableProperty;
import org.compass.annotations.SearchableReference;
import org.compass.annotations.Store;

@Entity
@Searchable(poly=true)
public class User {
    String id;
    String name;
    String address;
    Role r ;

    @Id
    @Column(name = "id")
    //@GenericGenerator(strategy = "uuid.hex", name = "uuidGen")
//    @GeneratedValue(generator = "uuidGen")
    @SearchableId
    public String getId() {
        return id;
    }

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

    @SearchableProperty(index = Index.ANALYZED, store = Store.YES)
    public String getName() {
        return name;
    }

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

    @SearchableProperty(index = Index.ANALYZED, store = Store.YES)
    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

     //@SearchableComponent
    @SearchableReference
    @ManyToOne
    @JoinColumn(name="roleId" )
    public Role getR() {
        return r;
    }

    public void setR(Role r) {
        this.r = r;
    }


}

=========================================================

package org.jixiuf.pojo;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import org.compass.annotations.Index;
import org.compass.annotations.Searchable;
import org.compass.annotations.SearchableId;
import org.compass.annotations.SearchableProperty;
import org.compass.annotations.Store;

@Entity
@Table(name = "role_")
@Searchable(poly=true)
public class Role {
    String id;
    String name;
    @SearchableId
    @Id
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    @SearchableProperty(index=Index.UN_TOKENIZED,store=Store.YES)
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }


}

=========================================================

package org.jixiuf.pojo;

import org.compass.core.Compass;
import org.compass.core.CompassHits;
import org.compass.core.CompassSession;
import org.compass.core.Property;
import org.compass.core.Resource;
import org.compass.gps.CompassGps;
import org.compass.gps.device.hibernate.embedded.HibernateHelper;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.junit.Before;
import org.junit.Test;

public class Test1 {
    SessionFactory sf = null;

    @Before
    public void setUp() {
        Configuration cfg = new AnnotationConfiguration().configure();
        sf = cfg.buildSessionFactory();
    }

    @Test
    /**
     * 存一个User 到数据库 这里没有一句是关于compass ,都 是hibernate 操作数据库的语句 ,但是此方法执行完后


在target/index  目录 下就会有关于User role 的索引   
   */
    public void testSaveInDb() {
        Session s = sf.openSession();
        Transaction tx = s.beginTransaction();
        Role r = new Role();
        r.setId("00000003");
        r.setName("admin");

        User u = new User();
        u.setR(r);
        u.setId("000001");
        u.setName("jixiuf");
        u.setAddress("山东临沂");
        u.setR(r);

        s.save(r);
        s.save(u);
        tx.commit();

    }
//这个方法用于同步数据库中的数据到索引目录中,即手动执行同步操作

//可以用来防止 不通过hibernate 而通过其他方法向数据库中更新数据,导致 数据不同步,

//可以通过 一个定时器,每隔一段时间检查一下数据是否有差异,扫行下面的方法
    @Test
    public void testIndex() {

        CompassGps gps = HibernateHelper.getCompassGps(sf);
        gps.index();

    }

    @Test
    /**
     * 从索引中查询User   ,查询索引中的User.name=admin 的数据
     */
    public void testFindFromCompass() {
        Compass compass = HibernateHelper.getCompass(sf);
        CompassSession session = compass.openSession();

        // CompassHits hits = session.find("jixiuf");
        CompassHits hits = session.queryBuilder()
                .term("$/User/r/name", "admin").hits();
        System.out.println(hits.length());
        for (int i = 0; i < hits.length(); i++) {
            User u = (User) hits.data(i);
            System.out.println(u.getId());
        }

    }


    @Test
    public void testAlias() {
        Compass compass = HibernateHelper.getCompass(sf);
        CompassSession session = compass.openSession();

        // CompassHits hits = session.find("jixiuf");
        CompassHits hits = session.queryBuilder().alias(
                User.class.getSimpleName()).hits();
        System.out.println(hits.length());
        for (int i = 0; i < hits.length(); i++) {
            Resource r = hits.resource(i);
            Property[] ps = r.getProperties();
            for (Property p : ps) {
                System.out.println(p.getName());

            }
        }

    }
}

==================================================================

另 一个同步数据 的代码

 

    public void testIndexUserFromDb() {
        Compass compass = CompassUtil.getCompass();
        CompassGps gps = new SingleCompassGps(compass);

        CompassGpsDevice device1 = new HibernateGpsDevice("h", sf);
        device1.setName("device1");
        gps.addGpsDevice(device1);

        gps.start();

        gps.index(User.class);
        gps.start();

        gps.stop();

    }

 

 

package org.jixiuf.compass.util;

import org.compass.annotations.config.CompassAnnotationsConfiguration;
import org.compass.core.Compass;
import org.compass.core.config.CompassConfiguration;

public class CompassUtil {

    public static Compass getCompass() {
        // CompassConfiguration conf = new
        // CompassAnnotationsConfiguration().addScan("org/jixiuf/compass/pojo").configure();
        CompassConfiguration conf = new CompassAnnotationsConfiguration()
                .addScan("org.jixiuf.pojo");

        // CompassConfiguration conf= new CompassAnnotationsConfiguration()
        // 注意这里的配置可以从compass reference 中查看到,其中的default 字为默认的highlighter
        // ,也可以是你自定认一个
        // compass.engine.highlighter.jixiufffffffffffffff.formatter.simple.pre
        // CompassHighlighterInstance.setHighlighter("jixiufffffffffffffff");
        conf.setSetting(
                "compass.engine.highlighter.default.formatter.simple.pre",
                "<span    style=' color:red'>");
        conf.setSetting(
                "compass.engine.highlighter.default.formatter.simple.post",
                "</span>");

        conf.setSetting(
                "compass.engine.highlighter.jixiuf.formatter.simple.pre",
                "<span name='jixiuf' ,style=' color:red'>");
        conf.setSetting(
                "compass.engine.highlighter.jixiuf.formatter.simple.post",
                "</span>");

        conf.configure();
        Compass compass = conf.buildCompass();

        return compass;
    }
}

=========================================

关于事务

Compass integrates with Hibernate transaction synchronization services.

compass 的事务与hibernate 同步,即hibernate 用什么控制事务,它也一样,如Jta, JDBC, ...

whichever Hibernate transaction management is used (Jta, JDBC, ...) you are using the same one、

 

the HibernateSyncTransaction will synchronize with the transaction upon transaction completion

 

 

If you are using the HibernateSyncTransaction , a Hibernate based transaction must already be started in order for HibernateSyncTransaction to join、

 

 

In order to configure Compass to work with the HiberanteSyncTransaction , you must set the compass.transaction.factory to org.compass.gps.device.hiberante.transaction.HibernateSyncTransactionFactory . Additional initialization should be performed by calling HibernateSyncTransactionFactory.setSessionFactory with Hibernate SessionFactory instance before the Compass is created.

为了配置compass 使用HiberanteSyncTransaction 控制事务,

compass.transaction.factory 属性要配成 org.compass.gps.device.hiberante.transaction.HibernateSyncTransactionFactory

并且成Compass 对象创建之前要运行 HibernateSyncTransactionFactory.setSessionFactory ()


 

compass.transaction.factory 可以在compass.cfg.xml 中配置,

也可以在代码 中配置,

但是自己感觉 这个代码多少有点不妥,因为 CompassConfiguration 需要自己配置在 compass.cfg.xml 中

或者像下面一样,每进行一个操作要新建 一个 CompassConfiguration ,感觉 compass 应该给一个获得 CompassConfiguration   对象的方法,像 Compass compass = HibernateHelper.getCompass(sf); 一样

     public void tetTx() {
        CompassConfiguration conf = new CompassAnnotationsConfiguration()
                .addScan("org.jixiuf.pojo")
                .setSetting("compass.transaction.factory",
                        "org.compass.gps.device.hiberante.transaction.HibernateSyncTransactionFactory");

        HibernateSyncTransactionFactory.setSessionFactory(sf);

        Compass compass = conf.buildCompass();
        Session hibernateSession = sf.openSession();
        hibernateSession.beginTransaction();
        hibernateSession.save(null);
        CompassSession compassSession =compass.openSession();
        compassSession.save(null);
        
        
        
        hibernateSession.getTransaction().commit();

    }

 

另外一个不太明白 的地方是,compass 自动 进行了数据的同步(即我只需用hibernate 往数据库中插数据,不用往compass 中插),又何必,配置事务,做往数据库中插入数据和往compass 中插入数据 的管理 呢

 

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值