package cn.search.pojo;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.search.annotations.DocumentId;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.Store;
@Entity
@Table(name = "search_foo")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Indexed(index = "search_foo")
public class Foo implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@DocumentId
@Field(name = "id", index = Index.TOKENIZED, store = Store.YES)
private Integer id;
@Column(nullable = false, length = 200)
@Field(name = "name", index = Index.TOKENIZED, store = Store.YES)
private String name;
@Column(nullable = false, length = 200)
@Field(name = "title", index = Index.TOKENIZED, store = Store.YES)
private String title;
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 getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
<?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" >
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.Oracle9Dialect
</property>
<property name="hibernate.connection.url">
jdbc:oracle:thin:@192.168.0.21:1521:oradb
</property>
<property name="hibernate.connection.username">
goodsres
</property>
<property name="hibernate.connection.password">
goodsres
</property>
<property name="hibernate.connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<property name="hibernate.search.default.directory_provider">
org.hibernate.search.store.FSDirectoryProvider
</property>
<property name="hibernate.search.default.indexBase">
e:/index
</property>
<property name="hibernate.cache.provider_class">
org.hibernate.cache.HashtableCacheProvider
</property>
<mapping class="cn.search.pojo.Foo" />
</session-factory>
</hibernate-configuration>
3銆佹祴璇曚唬鐮?br />
package cn.search.manager;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
import java.util.List;
import org.apache.lucene.analysis.StopAnalyzer;
import org.apache.lucene.queryParser.QueryParser;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import cn.search.pojo.Foo;
public class SearchResultsHibernate {
private static SessionFactory sf = null;
private static Session session = null;
private static Transaction tx = null;
@BeforeClass
public static void setupBeforeClass() throws Exception {
sf = new AnnotationConfiguration().configure("hibernate.cfg.xml")
.buildSessionFactory();
assertNotNull(sf);
}
@Before
public void setUp() throws Exception {
session = sf.openSession();
tx = session.beginTransaction();
tx.begin();
}
@After
public void tearDown() throws Exception {
tx.commit();
session.close();
}
public static void tearDownAfterClass() throws Exception {
if (sf != null)
sf.close();
}
@Test
public void testAddDept() throws Exception {
Foo foo = new Foo();
foo.setId(1);
foo.setName("絎竴涓猦ibernate search");
foo.setTitle("濂藉ソ瀛︿範錛屽ぉ澶╁悜涓?);
session.delete(foo);
}
@Test
public void testIndex() throws Exception {
FullTextSession fullTextSession = Search.createFullTextSession(session);
assertNotNull(session);
QueryParser parser = new QueryParser("title", new StopAnalyzer());
org.apache.lucene.search.Query luceneQuery = parser.parse("濂藉ソ瀛︿範");
Query hibQuery = fullTextSession.createFullTextQuery(luceneQuery,
Foo.class);
List list = hibQuery.list();
assertTrue(list.size() > 0);
}
public static void main(String[] args) {
try {
setupBeforeClass();
SearchResultsHibernate searchResults = new SearchResultsHibernate();
searchResults.setUp();
searchResults.testAddDept();
searchResults.tearDown();
SearchResultsHibernate.tearDownAfterClass();
} catch (Exception e) {
e.printStackTrace();
}
}
}
鎴戜滑鐨勬濊礬鏄厛鍐欎竴涓狟aseDao錛屼豢鐓ibernateTemplate錛屽皢鍩烘湰鍔熻兘鍏ㄩ儴瀹炵幇錛?/p>
public class BaseDao extends HibernateDaoSupport{
private Log log = LogFactory.getLog(getClass());
public Session openSession() {
return SessionFactoryUtils.getSession(getSessionFactory(), false);
}
public Object get(Class entityClass, Serializable id) throws DataAccessException {
Session session = openSession();
try {
return session.get(entityClass, id);
}
catch (HibernateException ex) {
throw SessionFactoryUtils.convertHibernateAccessException(ex);
}
}
public Serializable create(Object entity) throws DataAccessException {
Session session = openSession();
try {
return session.save(entity);
}
catch (HibernateException ex) {
throw SessionFactoryUtils.convertHibernateAccessException(ex);
}
}
...
鍏跺畠鐨凞AO錛屼粠BaseDao緇ф壙鍑烘潵錛岃繖鏍峰啓鍏朵粬鐨凞AO錛屼唬鐮佸氨浼氬緢灝戙?/p>
浠嶣aseDao緇ф壙鍑烘潵EntityDao錛屼笓闂ㄨ礋璐d竴鑸疄浣撶殑鍩烘湰鎿嶄綔錛屼細鏇存柟渚褲?/p>
public interface EntityDao {
public Object get(Class entityClass, Serializable id) throws DataAccessException;
public Object load(Class entityClass, Serializable id) throws DataAccessException;
public Serializable create(Object entity) throws DataAccessException;
...}
/**
* Base class for Hibernate DAOs. This class defines common CRUD methods for
* child classes to inherit. User Sping AOP Inteceptor
*/
public class EntityDaoImpl extends BaseDao implements EntityDao{
}
涓轟簡Transaction鐨勬帶鍒訛紝閲囩敤AOP鐨勬柟寮忥細
public interface EntityManager {
public Object get(Class entityClass, Serializable id);
public Object load(Class entityClass, Serializable id);
public Serializable create(Object entity);
...
}
/**
* Base class for Entity Service. User Sping AOP Inteceptor
*/
public class EntityManagerImpl implements EntityManager {
private EntityDao entityDao;
public void setEntityDao(EntityDao entityDao) {
this.entityDao = entityDao;
}
public Object get(Class entityClass, Serializable id) {
return entityDao.get(entityClass, id);
}
public Object load(Class entityClass, Serializable id) {
return entityDao.load(entityClass, id);
}
...
}
榪欐牱鎴戜滑灝辨湁浜嗕竴涓氱敤鐨凥ibernate瀹炰綋寮曟搸錛屽彲浠ュ浠諱綍Hibernate瀹炰綋瀹炵幇鍩烘湰鐨勫鍔犮佷慨鏀廣佸垹闄ゃ佹煡璇㈢瓑銆?/p>
鍏跺畠鐨凚usinessService灝卞彲浠ョ戶鎵縀ntityManager錛屽揩閫熷疄鐜頒笟鍔¢昏緫銆?/p>
鍏蜂綋XML閰嶇疆濡備笅錛?/p>
<!-- Oracle JNDI DataSource for J2EE environments -->
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName"><value>java:comp/env/jdbc/testPool</value></property>
</bean>
<!-- Hibernate SessionFactory for Oracle -->
<!-- Choose the dialect that matches your "dataSource" definition -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
<property name="dataSource"><ref local="dataSource"/></property>
<property name="mappingResources">
<value>user-hbm.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">net.sf.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.Provider</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<!-- AOP DAO Intecepter -->
<bean id="hibernateInterceptor" class="org.springframework.orm.hibernate.HibernateInterceptor">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean id="entityDaoTarget" class="com.gpower.services.entity.dao.EntityDaoImpl">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean id="entityDao" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>com.gpower.services.entity.dao.EntityDao</value>
</property>
<property name="interceptorNames">
<list>
<value>hibernateInterceptor</value>
<value>entityDaoTarget</value>
</list>
</property>
</bean>
<!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
<bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager">
<property name="sessionFactory"><ref local="sessionFactory"/></property>
</bean>
<!-- Transaction manager that delegates to JTA (for a transactional JNDI DataSource) -->
<!--
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>
-->
<!-- Transactional proxy for the Application primary business object -->
<bean id="entityManagerTarget" class="com.gpower.services.entity.EntityManagerImpl">
<property name="entityDao">
<ref bean="entityDao"/>
</property>
</bean>
<bean id="entityManager" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager"/>
</property>
<property name="target">
<ref bean="entityManagerTarget"/>
</property>
<property name="transactionAttributes">
<props>
<prop key="get*">PROPAGATION_SUPPORTS</prop>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>