- 浏览: 549990 次
- 性别:
- 来自: 北京
文章分类
最新评论
-
jsdsh:
自己写的就是不一样.
Spring3 MVC 注解(二)---@RequestMapping -
jsdsh:
吼,非常吼.学习了
Spring3 MVC 注解(一)---注解基本配置及@controller和 @RequestMapping 常用解释 -
爱情是一种错觉:
我爱你 i love 你[color=red][/color] ...
Spring3 MVC 注解(一)---注解基本配置及@controller和 @RequestMapping 常用解释 -
fs08ab:
大哥,目前这个问题有什么可靠的解决方案吗
@ResponseBody注解 -
lhs295988029:
说的很清楚,明白了~
Spring3 MVC 注解(一)---注解基本配置及@controller和 @RequestMapping 常用解释
1.去官方网站下载compass的jar包,我用的的2.1版本
http://www.compass-project.org/
ProductInfo.java
Java代码
1.@Entity
2.@Searchable
3.public class ProductInfo implements Serializable{
4. private static final long serialVersionUID = -8860864584425256200L;
5. private Integer id;
6. /** 货号 **/
7. private String code;
8. /** 产品名称 **/
9. private String name;
10. /** 产品类型 **/
11. private ProductType type;
12. /** 产品样式 **/
13. private Set<ProductStyle> styles = new HashSet<ProductStyle>();
14.
15. public ProductInfo() {}
16.
17. @OneToMany(cascade={CascadeType.REMOVE,CascadeType.PERSIST}, mappedBy="product",fetch=FetchType.EAGER)
18. @OrderBy("visible desc, id asc")
19. @SearchableReference
20. public Set<ProductStyle> getStyles() {
21. return styles;
22. }
23. public void setStyles(Set<ProductStyle> styles) {
24. this.styles = styles;
25. }
26.
27.
28. @Id @GeneratedValue
29. @SearchableId
30. public Integer getId() {
31. return id;
32. }
33. public void setId(Integer id) {
34. this.id = id;
35. }
36. @Column(length=30)
37. @SearchableProperty(index = Index.TOKENIZED, store = Store.YES)
38. public String getCode() {
39. return code;
40. }
41. public void setCode(String code) {
42. this.code = code;
43. }
44. @Column(length=50,nullable=false)
45. @SearchableProperty(index = Index.TOKENIZED, store = Store.YES)
46. public String getName() {
47. return name;
48. }
49. public void setName(String name) {
50. this.name = name;
51. }
52.
53. @ManyToOne(cascade=CascadeType.REFRESH,optional=false)
54. @JoinColumn(name="typeid")
55. @SearchableReference
56. public ProductType getType() {
57. return type;
58. }
59. public void setType(ProductType type) {
60. this.type = type;
61. }
62.
63.
64. @Override
65. public int hashCode() {
66. final int prime = 31;
67. int result = 1;
68. result = prime * result + ((id == null) ? 0 : id.hashCode());
69. return result;
70. }
71. @Override
72. public boolean equals(Object obj) {
73. if (this == obj)
74. return true;
75. if (obj == null)
76. return false;
77. if (getClass() != obj.getClass())
78. return false;
79. final ProductInfo other = (ProductInfo) obj;
80. if (id == null) {
81. if (other.id != null)
82. return false;
83. } else if (!id.equals(other.id))
84. return false;
85. return true;
86. }
87.}
@Entity
@Searchable
public class ProductInfo implements Serializable{
private static final long serialVersionUID = -8860864584425256200L;
private Integer id;
/** 货号 **/
private String code;
/** 产品名称 **/
private String name;
/** 产品类型 **/
private ProductType type;
/** 产品样式 **/
private Set<ProductStyle> styles = new HashSet<ProductStyle>();
public ProductInfo() {}
@OneToMany(cascade={CascadeType.REMOVE,CascadeType.PERSIST}, mappedBy="product",fetch=FetchType.EAGER)
@OrderBy("visible desc, id asc")
@SearchableReference
public Set<ProductStyle> getStyles() {
return styles;
}
public void setStyles(Set<ProductStyle> styles) {
this.styles = styles;
}
@Id @GeneratedValue
@SearchableId
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(length=30)
@SearchableProperty(index = Index.TOKENIZED, store = Store.YES)
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Column(length=50,nullable=false)
@SearchableProperty(index = Index.TOKENIZED, store = Store.YES)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToOne(cascade=CascadeType.REFRESH,optional=false)
@JoinColumn(name="typeid")
@SearchableReference
public ProductType getType() {
return type;
}
public void setType(ProductType type) {
this.type = type;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final ProductInfo other = (ProductInfo) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
ProductType.java
Java代码
1.
2.@Entity
3.@Searchable
4.public class ProductType implements Serializable{
5. private static final long serialVersionUID = 8106351120886053881L;
6. /** 类别id **/
7. private Integer typeid;
8. /** 类别名称 **/
9. private String name;
10. /** 子类别 **/
11. private Set<ProductType> childtypes = new HashSet<ProductType>();
12. /** 所属父类 **/
13. private ProductType parent;
14.
15. private Set<ProductInfo> products = new HashSet<ProductInfo>();
16.
17. @OneToMany(mappedBy="type", cascade=CascadeType.REMOVE)
18. @SearchableReference
19. public Set<ProductInfo> getProducts() {
20. return products;
21. }
22.
23. public void setProducts(Set<ProductInfo> products) {
24. this.products = products;
25. }
26.
27. public ProductType() {}
28.
29.
30. @ManyToOne(cascade=CascadeType.REFRESH)
31. @JoinColumn(name="parentid")
32. public ProductType getParent() {
33. return parent;
34. }
35.
36. public void setParent(ProductType parent) {
37. this.parent = parent;
38. }
39. @OneToMany(cascade={CascadeType.REFRESH,CascadeType.REMOVE},mappedBy="parent")
40. public Set<ProductType> getChildtypes() {
41. return childtypes;
42. }
43.
44. public void setChildtypes(Set<ProductType> childtypes) {
45. this.childtypes = childtypes;
46. }
47.
48. @Column(length=36,nullable=false)
49. public String getName() {
50. return name;
51. }
52.
53. public void setName(String name) {
54. this.name = name;
55. }
56.
57. @Id @GeneratedValue(strategy=GenerationType.AUTO)
58. @SearchableId
59. public Integer getTypeid() {
60. return typeid;
61. }
62.
63. public void setTypeid(Integer typeid) {
64. this.typeid = typeid;
65. }
66.
67. @Override
68. public int hashCode() {
69. final int prime = 31;
70. int result = 1;
71. result = prime * result + ((typeid == null) ? 0 : typeid.hashCode());
72. return result;
73. }
74.
75. @Override
76. public boolean equals(Object obj) {
77. if (this == obj)
78. return true;
79. if (obj == null)
80. return false;
81. if (getClass() != obj.getClass())
82. return false;
83. final ProductType other = (ProductType) obj;
84. if (typeid == null) {
85. if (other.typeid != null)
86. return false;
87. } else if (!typeid.equals(other.typeid))
88. return false;
89. return true;
90. }
91.}
@Entity
@Searchable
public class ProductType implements Serializable{
private static final long serialVersionUID = 8106351120886053881L;
/** 类别id **/
private Integer typeid;
/** 类别名称 **/
private String name;
/** 子类别 **/
private Set<ProductType> childtypes = new HashSet<ProductType>();
/** 所属父类 **/
private ProductType parent;
private Set<ProductInfo> products = new HashSet<ProductInfo>();
@OneToMany(mappedBy="type", cascade=CascadeType.REMOVE)
@SearchableReference
public Set<ProductInfo> getProducts() {
return products;
}
public void setProducts(Set<ProductInfo> products) {
this.products = products;
}
public ProductType() {}
@ManyToOne(cascade=CascadeType.REFRESH)
@JoinColumn(name="parentid")
public ProductType getParent() {
return parent;
}
public void setParent(ProductType parent) {
this.parent = parent;
}
@OneToMany(cascade={CascadeType.REFRESH,CascadeType.REMOVE},mappedBy="parent")
public Set<ProductType> getChildtypes() {
return childtypes;
}
public void setChildtypes(Set<ProductType> childtypes) {
this.childtypes = childtypes;
}
@Column(length=36,nullable=false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Id @GeneratedValue(strategy=GenerationType.AUTO)
@SearchableId
public Integer getTypeid() {
return typeid;
}
public void setTypeid(Integer typeid) {
this.typeid = typeid;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((typeid == null) ? 0 : typeid.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final ProductType other = (ProductType) obj;
if (typeid == null) {
if (other.typeid != null)
return false;
} else if (!typeid.equals(other.typeid))
return false;
return true;
}
}
ProductStyle.java
Java代码
1.
2.@Entity
3.@Searchable
4.public class ProductStyle implements Serializable{
5. private static final long serialVersionUID = -4926119953511144279L;
6. private Integer id;
7. /** 样式的名称 **/
8. private String name;
9. /** 图片 **/
10. private String imagename;
11. private String image140FullPath;
12. /** 是否可见 **/
13. private Boolean visible = true;
14. private ProductInfo product;
15.
16. public ProductStyle() {}
17.
18. public ProductStyle(Integer id) {
19. this.id = id;
20. }
21.
22. public ProductStyle(String name, String imagename) {
23. this.name = name;
24. this.imagename = imagename;
25. }
26. @ManyToOne(cascade=CascadeType.REFRESH,optional=false)
27. @JoinColumn(name="productid")
28. @SearchableReference
29. public ProductInfo getProduct() {
30. return product;
31. }
32. public void setProduct(ProductInfo product) {
33. this.product = product;
34. }
35. @Id @GeneratedValue
36. @SearchableId
37. public Integer getId() {
38. return id;
39. }
40. public void setId(Integer id) {
41. this.id = id;
42. }
43. @Column(length=30,nullable=false)
44. public String getName() {
45. return name;
46. }
47. public void setName(String name) {
48. this.name = name;
49. }
50. @Column(length=40,nullable=false)
51. @SearchableProperty(index = Index.UN_TOKENIZED, store = Store.YES)
52. public String getImagename() {
53. return imagename;
54. }
55. public void setImagename(String imagename) {
56. this.imagename = imagename;
57. }
58. @Column(nullable=false)
59. public Boolean getVisible() {
60. return visible;
61. }
62. public void setVisible(Boolean visible) {
63. this.visible = visible;
64. }
65. @Transient
66. public String getImageFullPath(){
67. return "/images/product/"+ this.getProduct().getType().getTypeid()+ "/"+
68. this.getProduct().getId()+ "/prototype/"+ this.imagename;
69. }
70.
71. @Transient
72. public String getImage140FullPath(){
73. image140FullPath = "/images/product/"+ this.getProduct().getType().getTypeid()+ "/"+
74. this.getProduct().getId()+ "/140x/"+ this.imagename;
75. return image140FullPath;
76. }
77.
78. @Override
79. public int hashCode() {
80. final int prime = 31;
81. int result = 1;
82. result = prime * result + ((id == null) ? 0 : id.hashCode());
83. return result;
84. }
85. @Override
86. public boolean equals(Object obj) {
87. if (this == obj)
88. return true;
89. if (obj == null)
90. return false;
91. if (getClass() != obj.getClass())
92. return false;
93. final ProductStyle other = (ProductStyle) obj;
94. if (id == null) {
95. if (other.id != null)
96. return false;
97. } else if (!id.equals(other.id))
98. return false;
99. return true;
100. }
101.}
@Entity
@Searchable
public class ProductStyle implements Serializable{
private static final long serialVersionUID = -4926119953511144279L;
private Integer id;
/** 样式的名称 **/
private String name;
/** 图片 **/
private String imagename;
private String image140FullPath;
/** 是否可见 **/
private Boolean visible = true;
private ProductInfo product;
public ProductStyle() {}
public ProductStyle(Integer id) {
this.id = id;
}
public ProductStyle(String name, String imagename) {
this.name = name;
this.imagename = imagename;
}
@ManyToOne(cascade=CascadeType.REFRESH,optional=false)
@JoinColumn(name="productid")
@SearchableReference
public ProductInfo getProduct() {
return product;
}
public void setProduct(ProductInfo product) {
this.product = product;
}
@Id @GeneratedValue
@SearchableId
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(length=30,nullable=false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(length=40,nullable=false)
@SearchableProperty(index = Index.UN_TOKENIZED, store = Store.YES)
public String getImagename() {
return imagename;
}
public void setImagename(String imagename) {
this.imagename = imagename;
}
@Column(nullable=false)
public Boolean getVisible() {
return visible;
}
public void setVisible(Boolean visible) {
this.visible = visible;
}
@Transient
public String getImageFullPath(){
return "/images/product/"+ this.getProduct().getType().getTypeid()+ "/"+
this.getProduct().getId()+ "/prototype/"+ this.imagename;
}
@Transient
public String getImage140FullPath(){
image140FullPath = "/images/product/"+ this.getProduct().getType().getTypeid()+ "/"+
this.getProduct().getId()+ "/140x/"+ this.imagename;
return image140FullPath;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final ProductStyle other = (ProductStyle) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
这里要特别注意有集合类型要搜索或显示的时候,两边定义的@SearchableReference或 @SearchableComponent必须一致
2.再spring的配置文件中加入以下代码
Java代码
1.
2.<bean id="annotationConfiguration" class="org.compass.annotations.config.CompassAnnotationsConfiguration">
3.</bean>
4. <!-- compass Bean -->
5.<bean id="compass" class="org.compass.spring.LocalCompassBean">
6. <property name="compassConfiguration"
7. ref="annotationConfiguration" />
8. <property name="transactionManager" ref="txManager" />
9. <property name="compassSettings">
10. <props>
11. <!-- 定义索引的存储位置 -->
12.<prop key="compass.engine.connection">d:/compass</prop>
13.<prop key="compass.transaction.factory">
14. org.compass.spring.transaction.SpringSyncTransactionFactory
15.</prop>
16. <!-- 定义分词器-->
17.<prop key="compass.engine.analyzer.MMAnalyzer.CustomAnalyzer">
18.org.mira.lucene.analysis.IK_CAnalyzer
19.</prop>
20.</props>
21.</property>
22. <property name="resourceDirectoryLocations">
23. <list>
24. <value>classpath:net/shopin/bean/product</value>
25. </list>
26. </property>
27.
28. </bean>
29.
30. <bean id="jpaGpsDevice"
31. class="org.compass.gps.device.jpa.JpaGpsDevice">
32. <property name="name">
33. <value>JpaGpsDevice</value>
34. </property>
35. <property name="entityManagerFactory"
36. ref="entityManagerFactory" />
37. <property name="mirrorDataChanges">
38. <value>true</value>
39. </property>
40. </bean>
41. <!-- 数据库中的数据变化后同步更新索引 -->
42. <bean id="compassGps" class="org.compass.gps.impl.SingleCompassGps"
43. init-method="start" destroy-method="stop">
44. <property name="compass" ref="compass" />
45. <property name="gpsDevices">
46. <list>
47. <bean
48. class="org.compass.spring.device.SpringSyncTransactionGpsDeviceWrapper">
49. <property name="gpsDevice" ref="jpaGpsDevice" />
50. </bean>
51. </list>
52. </property>
53. </bean>
54.
55.
56. <bean id="compassTemplate"
57. class="org.compass.core.CompassTemplate">
58. <property name="compass" ref="compass" />
59. </bean>
60.
61. <!-- 定时重建索引(利用quartz)或随Spring ApplicationContext启动而重建索引 -->
62. <bean id="compassIndexBuilder"
63. class="net.shopin.service.search.impl.CompassIndexBuilder"
64. lazy-init="false">
65. <property name="compassGps" ref="compassGps" />
66. <property name="buildIndex" value="true" />
67. <property name="lazyTime" value="5" />
68. </bean>
<bean id="annotationConfiguration" class="org.compass.annotations.config.CompassAnnotationsConfiguration">
</bean>
<!-- compass Bean -->
<bean id="compass" class="org.compass.spring.LocalCompassBean">
<property name="compassConfiguration"
ref="annotationConfiguration" />
<property name="transactionManager" ref="txManager" />
<property name="compassSettings">
<props>
<!-- 定义索引的存储位置 -->
<prop key="compass.engine.connection">d:/compass</prop>
<prop key="compass.transaction.factory">
org.compass.spring.transaction.SpringSyncTransactionFactory
</prop>
<!-- 定义分词器-->
<prop key="compass.engine.analyzer.MMAnalyzer.CustomAnalyzer">
org.mira.lucene.analysis.IK_CAnalyzer
</prop>
</props>
</property>
<property name="resourceDirectoryLocations">
<list>
<value>classpath:net/shopin/bean/product</value>
</list>
</property>
</bean>
<bean id="jpaGpsDevice"
class="org.compass.gps.device.jpa.JpaGpsDevice">
<property name="name">
<value>JpaGpsDevice</value>
</property>
<property name="entityManagerFactory"
ref="entityManagerFactory" />
<property name="mirrorDataChanges">
<value>true</value>
</property>
</bean>
<!-- 数据库中的数据变化后同步更新索引 -->
<bean id="compassGps" class="org.compass.gps.impl.SingleCompassGps"
init-method="start" destroy-method="stop">
<property name="compass" ref="compass" />
<property name="gpsDevices">
<list>
<bean
class="org.compass.spring.device.SpringSyncTransactionGpsDeviceWrapper">
<property name="gpsDevice" ref="jpaGpsDevice" />
</bean>
</list>
</property>
</bean>
<bean id="compassTemplate"
class="org.compass.core.CompassTemplate">
<property name="compass" ref="compass" />
</bean>
<!-- 定时重建索引(利用quartz)或随Spring ApplicationContext启动而重建索引 -->
<bean id="compassIndexBuilder"
class="net.shopin.service.search.impl.CompassIndexBuilder"
lazy-init="false">
<property name="compassGps" ref="compassGps" />
<property name="buildIndex" value="true" />
<property name="lazyTime" value="5" />
</bean>
3.自动建立索引的java bean
Java代码
1.
2./**
3. * 通过quartz定时调度定时重建索引或自动随Spring ApplicationContext启动而重建索引的Builder.
4. * 会启动后延时数秒新开线程调用compassGps.index()函数.
5. * 默认会在Web应用每次启动时重建索引,可以设置buildIndex属性为false来禁止此功能.
6. * 也可以不用本Builder, 编写手动调用compassGps.index()的代码.
7. *
8. */
9.public class CompassIndexBuilder implements InitializingBean {
10. // 是否需要建立索引,可被设置为false使本Builder失效.
11. private boolean buildIndex = false;
12.
13. // 索引操作线程延时启动的时间,单位为秒
14. private int lazyTime = 10;
15.
16. // Compass封装
17. private CompassGps compassGps;
18.
19. // 索引线程
20. private Thread indexThread = new Thread() {
21.
22. @Override
23. public void run() {
24. try {
25. Thread.sleep(lazyTime * 1000);
26. System.out.println("begin compass index...");
27. long beginTime = System.currentTimeMillis();
28. // 重建索引.
29. // 如果compass实体中定义的索引文件已存在,索引过程中会建立临时索引,
30. // 索引完成后再进行覆盖.
31. compassGps.index();
32. long costTime = System.currentTimeMillis() - beginTime;
33. System.out.println("compss index finished.");
34. System.out.println("costed " + costTime + " milliseconds");
35. } catch (InterruptedException e) {
36. e.printStackTrace();
37. }
38. }
39. };
40.
41. /**
42. * 实现<code>InitializingBean</code>接口,在完成注入后调用启动索引线程.
43. *
44. * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
45. */
46. public void afterPropertiesSet() throws Exception {
47. if (buildIndex) {
48. indexThread.setDaemon(true);
49. indexThread.setName("Compass Indexer");
50. indexThread.start();
51. }
52. }
53.
54. public void setBuildIndex(boolean buildIndex) {
55. this.buildIndex = buildIndex;
56. }
57.
58. public void setLazyTime(int lazyTime) {
59. this.lazyTime = lazyTime;
60. }
61.
62. public void setCompassGps(CompassGps compassGps) {
63. this.compassGps = compassGps;
64. }
65.}
/**
* 通过quartz定时调度定时重建索引或自动随Spring ApplicationContext启动而重建索引的Builder.
* 会启动后延时数秒新开线程调用compassGps.index()函数.
* 默认会在Web应用每次启动时重建索引,可以设置buildIndex属性为false来禁止此功能.
* 也可以不用本Builder, 编写手动调用compassGps.index()的代码.
*
*/
public class CompassIndexBuilder implements InitializingBean {
// 是否需要建立索引,可被设置为false使本Builder失效.
private boolean buildIndex = false;
// 索引操作线程延时启动的时间,单位为秒
private int lazyTime = 10;
// Compass封装
private CompassGps compassGps;
// 索引线程
private Thread indexThread = new Thread() {
@Override
public void run() {
try {
Thread.sleep(lazyTime * 1000);
System.out.println("begin compass index...");
long beginTime = System.currentTimeMillis();
// 重建索引.
// 如果compass实体中定义的索引文件已存在,索引过程中会建立临时索引,
// 索引完成后再进行覆盖.
compassGps.index();
long costTime = System.currentTimeMillis() - beginTime;
System.out.println("compss index finished.");
System.out.println("costed " + costTime + " milliseconds");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
/**
* 实现<code>InitializingBean</code>接口,在完成注入后调用启动索引线程.
*
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/
public void afterPropertiesSet() throws Exception {
if (buildIndex) {
indexThread.setDaemon(true);
indexThread.setName("Compass Indexer");
indexThread.start();
}
}
public void setBuildIndex(boolean buildIndex) {
this.buildIndex = buildIndex;
}
public void setLazyTime(int lazyTime) {
this.lazyTime = lazyTime;
}
public void setCompassGps(CompassGps compassGps) {
this.compassGps = compassGps;
}
}
4.建立索引Service 层代码
Java代码
1.
2.@Service
3.@Transactional
4.public class SearchServiceBean extends DaoSupport implements SearchService {
5. @Resource(name = "compass")
6. Compass compass;
7.
8./** 创建索引 **/
9.public void index(ProductInfo p) {
10.
11.CompassSession session = compass.openSession();
12.CompassTransaction tx = null;
13.try {
14. tx = session.beginTransaction();
15. session.create(p);
16. tx.commit();
17.} catch (Exception e) {
18. if (tx != null) {
19.tx.commit();
20. }
21. throw new RuntimeException(e);
22. } finally {
23. if (session != null) {
24. session.close();
25. }
26. }
27. }
28. /** 删除一条索引 **/
29. public void delete(ProductInfo p) {
30. CompassTemplate ct = new CompassTemplate(compass);
31. ct.delete(p);
32. }
33. /** 更新(重新创建)一条索引 **/
34. public void update(final ProductInfo p) {
35. CompassTemplate ct = new CompassTemplate(compass);
36.
37. CompassCallback<Object> action = new CompassCallback<Object>() {
38.
39. public Object doInCompass(CompassSession session)
40. throws CompassException {
41. session.delete(p);
42. session.create(p);
43. return null;
44. }
45.
46. };
47.
48. ct.execute(action);
49. }
50. /** 索引查询 **/
51. public List<ProductInfo> find(final String keywords) {
52. CompassTemplate ct = new CompassTemplate(compass);
53. return ct.execute(new CompassCallback<List<ProductInfo>>() {
54.
55. public List<ProductInfo> doInCompass(CompassSession session)
56. throws CompassException {
57. List<ProductInfo> result = new ArrayList<ProductInfo>();
58. CompassQueryBuilder queryBuilder = session.queryBuilder();
59. CompassHits hits = null; // session.find(query);
60. /** 在所有字段中查询 **/
61. CompassQuery allPropertyQuery = queryBuilder.queryString(keywords).toQuery();
62. hits = allPropertyQuery.hits();
63. /** 在指定字段中查询 **/
64. // CompassQuery query = queryBuilder.term("name", keywords);
65. // hits = query.hits();
66. /** 指定范围查询 **/
67.// CompassQuery dateRangeQuery =
68.// queryBuilder.between("postTime",startTime, endTime, true);
69.// hits = queryBuilder.bool()
70.// .addMust(allPropertyQuery)
71.// .addMust(dateRangeQuery)
72.// .toQuery()
73.// .hits();
74.// System.out.println("---------");
75. for (int i = 0; i < hits.length(); i++) {
76. ProductInfo p = (ProductInfo) hits.data(i);
77. /** 如果进行高亮的属性中没有出现关键字, 则返回null **/
78.// String ht = hits.highlighter(i).fragment("name");
79.// if (ht != null) {
80.// p.setName(ht);
81.// }
82.// String hc = hits.highlighter(i).fragment("code");
83.// if (hc != null) {
84.// p.setCode(hc);
85.// }
86. result.add(p);
87. }
88. return result;
89. }
90. });
91. }
@Service
@Transactional
public class SearchServiceBean extends DaoSupport implements SearchService {
@Resource(name = "compass")
Compass compass;
/** 创建索引 **/
public void index(ProductInfo p) {
CompassSession session = compass.openSession();
CompassTransaction tx = null;
try {
tx = session.beginTransaction();
session.create(p);
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.commit();
}
throw new RuntimeException(e);
} finally {
if (session != null) {
session.close();
}
}
}
/** 删除一条索引 **/
public void delete(ProductInfo p) {
CompassTemplate ct = new CompassTemplate(compass);
ct.delete(p);
}
/** 更新(重新创建)一条索引 **/
public void update(final ProductInfo p) {
CompassTemplate ct = new CompassTemplate(compass);
CompassCallback<Object> action = new CompassCallback<Object>() {
public Object doInCompass(CompassSession session)
throws CompassException {
session.delete(p);
session.create(p);
return null;
}
};
ct.execute(action);
}
/** 索引查询 **/
public List<ProductInfo> find(final String keywords) {
CompassTemplate ct = new CompassTemplate(compass);
return ct.execute(new CompassCallback<List<ProductInfo>>() {
public List<ProductInfo> doInCompass(CompassSession session)
throws CompassException {
List<ProductInfo> result = new ArrayList<ProductInfo>();
CompassQueryBuilder queryBuilder = session.queryBuilder();
CompassHits hits = null; // session.find(query);
/** 在所有字段中查询 **/
CompassQuery allPropertyQuery = queryBuilder.queryString(keywords).toQuery();
hits = allPropertyQuery.hits();
/** 在指定字段中查询 **/
// CompassQuery query = queryBuilder.term("name", keywords);
// hits = query.hits();
/** 指定范围查询 **/
// CompassQuery dateRangeQuery =
// queryBuilder.between("postTime",startTime, endTime, true);
// hits = queryBuilder.bool()
// .addMust(allPropertyQuery)
// .addMust(dateRangeQuery)
// .toQuery()
// .hits();
// System.out.println("---------");
for (int i = 0; i < hits.length(); i++) {
ProductInfo p = (ProductInfo) hits.data(i);
/** 如果进行高亮的属性中没有出现关键字, 则返回null **/
// String ht = hits.highlighter(i).fragment("name");
// if (ht != null) {
// p.setName(ht);
// }
// String hc = hits.highlighter(i).fragment("code");
// if (hc != null) {
// p.setCode(hc);
// }
result.add(p);
}
return result;
}
});
}
控制层
Java代码
1.@Controller("/search/gosearch")
2.public class SearchAction extends Action {
3. @Resource(name = "searchServiceBean")
4. private SearchService SearchService;
5.
6. @Override
7. public ActionForward execute(ActionMapping mapping, ActionForm form,
8. HttpServletRequest request, HttpServletResponse response)
9. throws Exception {
10. String keywords=request.getParameter("word").trim();
11. if(keywords==null||"".equals(keywords)){
12. return mapping.findForward("noproduct");
13. }
14. System.out.println("------"+keywords);
15. List<ProductInfo> list = SearchService.find(keywords);
16. request.setAttribute("word", keywords);
17. request.setAttribute("product",list);
18. if(list.isEmpty()){
19. return mapping.findForward("noproduct");
20. }else{
21. return mapping.findForward("list");
22.
23. }
24. }
25.}
@Controller("/search/gosearch")
public class SearchAction extends Action {
@Resource(name = "searchServiceBean")
private SearchService SearchService;
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String keywords=request.getParameter("word").trim();
if(keywords==null||"".equals(keywords)){
return mapping.findForward("noproduct");
}
System.out.println("------"+keywords);
List<ProductInfo> list = SearchService.find(keywords);
request.setAttribute("word", keywords);
request.setAttribute("product",list);
if(list.isEmpty()){
return mapping.findForward("noproduct");
}else{
return mapping.findForward("list");
}
}
}
junit测试
Java代码
1.public class SearchTest {
2.
3. private static AbstractApplicationContext context;
4. @BeforeClass
5. public static void setUpBeforeClass() throws Exception {
6. try {
7. context = new ClassPathXmlApplicationContext("beans.xml");
8. } catch (Exception e) {
9. e.printStackTrace();
10. }
11. }
12.
13. @Test
14. public void testDelete() {
15. SearchService searchService = (SearchService) context
16. .getBean("searchServiceBean");
17. ProductInfo p = new ProductInfo(2);
18. searchService.delete(p);
19. }
20.
21. @Test
22. public void createIndex(){
23. SearchService searchService = (SearchService) context
24. .getBean("searchServiceBean");
25. ProductInfoService productInfoService = (ProductInfoService) context
26. .getBean("productInfoServiceBean");
27. List<ProductInfo> list=productInfoService.getAllProduct();
28. for(ProductInfo productInfo:list){
29.// System.out.println("-------"+productInfo.getName());
30. searchService.index(productInfo);
31. }
32. }
33.
34. @Test
35. public void testSearch() {
36. SearchService searchService = (SearchService) context
37. .getBean("searchServiceBean");
38. String query = "手机";
39. List<ProductInfo> ProductInfos;
40.
41. ProductInfos = searchService.find(query);
42. for (ProductInfo p : ProductInfos) {
43. System.out.println(p.getName());
44. }
45. System.out.println("------------");
46. }
47.}
http://www.compass-project.org/
ProductInfo.java
Java代码
1.@Entity
2.@Searchable
3.public class ProductInfo implements Serializable{
4. private static final long serialVersionUID = -8860864584425256200L;
5. private Integer id;
6. /** 货号 **/
7. private String code;
8. /** 产品名称 **/
9. private String name;
10. /** 产品类型 **/
11. private ProductType type;
12. /** 产品样式 **/
13. private Set<ProductStyle> styles = new HashSet<ProductStyle>();
14.
15. public ProductInfo() {}
16.
17. @OneToMany(cascade={CascadeType.REMOVE,CascadeType.PERSIST}, mappedBy="product",fetch=FetchType.EAGER)
18. @OrderBy("visible desc, id asc")
19. @SearchableReference
20. public Set<ProductStyle> getStyles() {
21. return styles;
22. }
23. public void setStyles(Set<ProductStyle> styles) {
24. this.styles = styles;
25. }
26.
27.
28. @Id @GeneratedValue
29. @SearchableId
30. public Integer getId() {
31. return id;
32. }
33. public void setId(Integer id) {
34. this.id = id;
35. }
36. @Column(length=30)
37. @SearchableProperty(index = Index.TOKENIZED, store = Store.YES)
38. public String getCode() {
39. return code;
40. }
41. public void setCode(String code) {
42. this.code = code;
43. }
44. @Column(length=50,nullable=false)
45. @SearchableProperty(index = Index.TOKENIZED, store = Store.YES)
46. public String getName() {
47. return name;
48. }
49. public void setName(String name) {
50. this.name = name;
51. }
52.
53. @ManyToOne(cascade=CascadeType.REFRESH,optional=false)
54. @JoinColumn(name="typeid")
55. @SearchableReference
56. public ProductType getType() {
57. return type;
58. }
59. public void setType(ProductType type) {
60. this.type = type;
61. }
62.
63.
64. @Override
65. public int hashCode() {
66. final int prime = 31;
67. int result = 1;
68. result = prime * result + ((id == null) ? 0 : id.hashCode());
69. return result;
70. }
71. @Override
72. public boolean equals(Object obj) {
73. if (this == obj)
74. return true;
75. if (obj == null)
76. return false;
77. if (getClass() != obj.getClass())
78. return false;
79. final ProductInfo other = (ProductInfo) obj;
80. if (id == null) {
81. if (other.id != null)
82. return false;
83. } else if (!id.equals(other.id))
84. return false;
85. return true;
86. }
87.}
@Entity
@Searchable
public class ProductInfo implements Serializable{
private static final long serialVersionUID = -8860864584425256200L;
private Integer id;
/** 货号 **/
private String code;
/** 产品名称 **/
private String name;
/** 产品类型 **/
private ProductType type;
/** 产品样式 **/
private Set<ProductStyle> styles = new HashSet<ProductStyle>();
public ProductInfo() {}
@OneToMany(cascade={CascadeType.REMOVE,CascadeType.PERSIST}, mappedBy="product",fetch=FetchType.EAGER)
@OrderBy("visible desc, id asc")
@SearchableReference
public Set<ProductStyle> getStyles() {
return styles;
}
public void setStyles(Set<ProductStyle> styles) {
this.styles = styles;
}
@Id @GeneratedValue
@SearchableId
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(length=30)
@SearchableProperty(index = Index.TOKENIZED, store = Store.YES)
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Column(length=50,nullable=false)
@SearchableProperty(index = Index.TOKENIZED, store = Store.YES)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToOne(cascade=CascadeType.REFRESH,optional=false)
@JoinColumn(name="typeid")
@SearchableReference
public ProductType getType() {
return type;
}
public void setType(ProductType type) {
this.type = type;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final ProductInfo other = (ProductInfo) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
ProductType.java
Java代码
1.
2.@Entity
3.@Searchable
4.public class ProductType implements Serializable{
5. private static final long serialVersionUID = 8106351120886053881L;
6. /** 类别id **/
7. private Integer typeid;
8. /** 类别名称 **/
9. private String name;
10. /** 子类别 **/
11. private Set<ProductType> childtypes = new HashSet<ProductType>();
12. /** 所属父类 **/
13. private ProductType parent;
14.
15. private Set<ProductInfo> products = new HashSet<ProductInfo>();
16.
17. @OneToMany(mappedBy="type", cascade=CascadeType.REMOVE)
18. @SearchableReference
19. public Set<ProductInfo> getProducts() {
20. return products;
21. }
22.
23. public void setProducts(Set<ProductInfo> products) {
24. this.products = products;
25. }
26.
27. public ProductType() {}
28.
29.
30. @ManyToOne(cascade=CascadeType.REFRESH)
31. @JoinColumn(name="parentid")
32. public ProductType getParent() {
33. return parent;
34. }
35.
36. public void setParent(ProductType parent) {
37. this.parent = parent;
38. }
39. @OneToMany(cascade={CascadeType.REFRESH,CascadeType.REMOVE},mappedBy="parent")
40. public Set<ProductType> getChildtypes() {
41. return childtypes;
42. }
43.
44. public void setChildtypes(Set<ProductType> childtypes) {
45. this.childtypes = childtypes;
46. }
47.
48. @Column(length=36,nullable=false)
49. public String getName() {
50. return name;
51. }
52.
53. public void setName(String name) {
54. this.name = name;
55. }
56.
57. @Id @GeneratedValue(strategy=GenerationType.AUTO)
58. @SearchableId
59. public Integer getTypeid() {
60. return typeid;
61. }
62.
63. public void setTypeid(Integer typeid) {
64. this.typeid = typeid;
65. }
66.
67. @Override
68. public int hashCode() {
69. final int prime = 31;
70. int result = 1;
71. result = prime * result + ((typeid == null) ? 0 : typeid.hashCode());
72. return result;
73. }
74.
75. @Override
76. public boolean equals(Object obj) {
77. if (this == obj)
78. return true;
79. if (obj == null)
80. return false;
81. if (getClass() != obj.getClass())
82. return false;
83. final ProductType other = (ProductType) obj;
84. if (typeid == null) {
85. if (other.typeid != null)
86. return false;
87. } else if (!typeid.equals(other.typeid))
88. return false;
89. return true;
90. }
91.}
@Entity
@Searchable
public class ProductType implements Serializable{
private static final long serialVersionUID = 8106351120886053881L;
/** 类别id **/
private Integer typeid;
/** 类别名称 **/
private String name;
/** 子类别 **/
private Set<ProductType> childtypes = new HashSet<ProductType>();
/** 所属父类 **/
private ProductType parent;
private Set<ProductInfo> products = new HashSet<ProductInfo>();
@OneToMany(mappedBy="type", cascade=CascadeType.REMOVE)
@SearchableReference
public Set<ProductInfo> getProducts() {
return products;
}
public void setProducts(Set<ProductInfo> products) {
this.products = products;
}
public ProductType() {}
@ManyToOne(cascade=CascadeType.REFRESH)
@JoinColumn(name="parentid")
public ProductType getParent() {
return parent;
}
public void setParent(ProductType parent) {
this.parent = parent;
}
@OneToMany(cascade={CascadeType.REFRESH,CascadeType.REMOVE},mappedBy="parent")
public Set<ProductType> getChildtypes() {
return childtypes;
}
public void setChildtypes(Set<ProductType> childtypes) {
this.childtypes = childtypes;
}
@Column(length=36,nullable=false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Id @GeneratedValue(strategy=GenerationType.AUTO)
@SearchableId
public Integer getTypeid() {
return typeid;
}
public void setTypeid(Integer typeid) {
this.typeid = typeid;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((typeid == null) ? 0 : typeid.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final ProductType other = (ProductType) obj;
if (typeid == null) {
if (other.typeid != null)
return false;
} else if (!typeid.equals(other.typeid))
return false;
return true;
}
}
ProductStyle.java
Java代码
1.
2.@Entity
3.@Searchable
4.public class ProductStyle implements Serializable{
5. private static final long serialVersionUID = -4926119953511144279L;
6. private Integer id;
7. /** 样式的名称 **/
8. private String name;
9. /** 图片 **/
10. private String imagename;
11. private String image140FullPath;
12. /** 是否可见 **/
13. private Boolean visible = true;
14. private ProductInfo product;
15.
16. public ProductStyle() {}
17.
18. public ProductStyle(Integer id) {
19. this.id = id;
20. }
21.
22. public ProductStyle(String name, String imagename) {
23. this.name = name;
24. this.imagename = imagename;
25. }
26. @ManyToOne(cascade=CascadeType.REFRESH,optional=false)
27. @JoinColumn(name="productid")
28. @SearchableReference
29. public ProductInfo getProduct() {
30. return product;
31. }
32. public void setProduct(ProductInfo product) {
33. this.product = product;
34. }
35. @Id @GeneratedValue
36. @SearchableId
37. public Integer getId() {
38. return id;
39. }
40. public void setId(Integer id) {
41. this.id = id;
42. }
43. @Column(length=30,nullable=false)
44. public String getName() {
45. return name;
46. }
47. public void setName(String name) {
48. this.name = name;
49. }
50. @Column(length=40,nullable=false)
51. @SearchableProperty(index = Index.UN_TOKENIZED, store = Store.YES)
52. public String getImagename() {
53. return imagename;
54. }
55. public void setImagename(String imagename) {
56. this.imagename = imagename;
57. }
58. @Column(nullable=false)
59. public Boolean getVisible() {
60. return visible;
61. }
62. public void setVisible(Boolean visible) {
63. this.visible = visible;
64. }
65. @Transient
66. public String getImageFullPath(){
67. return "/images/product/"+ this.getProduct().getType().getTypeid()+ "/"+
68. this.getProduct().getId()+ "/prototype/"+ this.imagename;
69. }
70.
71. @Transient
72. public String getImage140FullPath(){
73. image140FullPath = "/images/product/"+ this.getProduct().getType().getTypeid()+ "/"+
74. this.getProduct().getId()+ "/140x/"+ this.imagename;
75. return image140FullPath;
76. }
77.
78. @Override
79. public int hashCode() {
80. final int prime = 31;
81. int result = 1;
82. result = prime * result + ((id == null) ? 0 : id.hashCode());
83. return result;
84. }
85. @Override
86. public boolean equals(Object obj) {
87. if (this == obj)
88. return true;
89. if (obj == null)
90. return false;
91. if (getClass() != obj.getClass())
92. return false;
93. final ProductStyle other = (ProductStyle) obj;
94. if (id == null) {
95. if (other.id != null)
96. return false;
97. } else if (!id.equals(other.id))
98. return false;
99. return true;
100. }
101.}
@Entity
@Searchable
public class ProductStyle implements Serializable{
private static final long serialVersionUID = -4926119953511144279L;
private Integer id;
/** 样式的名称 **/
private String name;
/** 图片 **/
private String imagename;
private String image140FullPath;
/** 是否可见 **/
private Boolean visible = true;
private ProductInfo product;
public ProductStyle() {}
public ProductStyle(Integer id) {
this.id = id;
}
public ProductStyle(String name, String imagename) {
this.name = name;
this.imagename = imagename;
}
@ManyToOne(cascade=CascadeType.REFRESH,optional=false)
@JoinColumn(name="productid")
@SearchableReference
public ProductInfo getProduct() {
return product;
}
public void setProduct(ProductInfo product) {
this.product = product;
}
@Id @GeneratedValue
@SearchableId
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(length=30,nullable=false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(length=40,nullable=false)
@SearchableProperty(index = Index.UN_TOKENIZED, store = Store.YES)
public String getImagename() {
return imagename;
}
public void setImagename(String imagename) {
this.imagename = imagename;
}
@Column(nullable=false)
public Boolean getVisible() {
return visible;
}
public void setVisible(Boolean visible) {
this.visible = visible;
}
@Transient
public String getImageFullPath(){
return "/images/product/"+ this.getProduct().getType().getTypeid()+ "/"+
this.getProduct().getId()+ "/prototype/"+ this.imagename;
}
@Transient
public String getImage140FullPath(){
image140FullPath = "/images/product/"+ this.getProduct().getType().getTypeid()+ "/"+
this.getProduct().getId()+ "/140x/"+ this.imagename;
return image140FullPath;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final ProductStyle other = (ProductStyle) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
这里要特别注意有集合类型要搜索或显示的时候,两边定义的@SearchableReference或 @SearchableComponent必须一致
2.再spring的配置文件中加入以下代码
Java代码
1.
2.<bean id="annotationConfiguration" class="org.compass.annotations.config.CompassAnnotationsConfiguration">
3.</bean>
4. <!-- compass Bean -->
5.<bean id="compass" class="org.compass.spring.LocalCompassBean">
6. <property name="compassConfiguration"
7. ref="annotationConfiguration" />
8. <property name="transactionManager" ref="txManager" />
9. <property name="compassSettings">
10. <props>
11. <!-- 定义索引的存储位置 -->
12.<prop key="compass.engine.connection">d:/compass</prop>
13.<prop key="compass.transaction.factory">
14. org.compass.spring.transaction.SpringSyncTransactionFactory
15.</prop>
16. <!-- 定义分词器-->
17.<prop key="compass.engine.analyzer.MMAnalyzer.CustomAnalyzer">
18.org.mira.lucene.analysis.IK_CAnalyzer
19.</prop>
20.</props>
21.</property>
22. <property name="resourceDirectoryLocations">
23. <list>
24. <value>classpath:net/shopin/bean/product</value>
25. </list>
26. </property>
27.
28. </bean>
29.
30. <bean id="jpaGpsDevice"
31. class="org.compass.gps.device.jpa.JpaGpsDevice">
32. <property name="name">
33. <value>JpaGpsDevice</value>
34. </property>
35. <property name="entityManagerFactory"
36. ref="entityManagerFactory" />
37. <property name="mirrorDataChanges">
38. <value>true</value>
39. </property>
40. </bean>
41. <!-- 数据库中的数据变化后同步更新索引 -->
42. <bean id="compassGps" class="org.compass.gps.impl.SingleCompassGps"
43. init-method="start" destroy-method="stop">
44. <property name="compass" ref="compass" />
45. <property name="gpsDevices">
46. <list>
47. <bean
48. class="org.compass.spring.device.SpringSyncTransactionGpsDeviceWrapper">
49. <property name="gpsDevice" ref="jpaGpsDevice" />
50. </bean>
51. </list>
52. </property>
53. </bean>
54.
55.
56. <bean id="compassTemplate"
57. class="org.compass.core.CompassTemplate">
58. <property name="compass" ref="compass" />
59. </bean>
60.
61. <!-- 定时重建索引(利用quartz)或随Spring ApplicationContext启动而重建索引 -->
62. <bean id="compassIndexBuilder"
63. class="net.shopin.service.search.impl.CompassIndexBuilder"
64. lazy-init="false">
65. <property name="compassGps" ref="compassGps" />
66. <property name="buildIndex" value="true" />
67. <property name="lazyTime" value="5" />
68. </bean>
<bean id="annotationConfiguration" class="org.compass.annotations.config.CompassAnnotationsConfiguration">
</bean>
<!-- compass Bean -->
<bean id="compass" class="org.compass.spring.LocalCompassBean">
<property name="compassConfiguration"
ref="annotationConfiguration" />
<property name="transactionManager" ref="txManager" />
<property name="compassSettings">
<props>
<!-- 定义索引的存储位置 -->
<prop key="compass.engine.connection">d:/compass</prop>
<prop key="compass.transaction.factory">
org.compass.spring.transaction.SpringSyncTransactionFactory
</prop>
<!-- 定义分词器-->
<prop key="compass.engine.analyzer.MMAnalyzer.CustomAnalyzer">
org.mira.lucene.analysis.IK_CAnalyzer
</prop>
</props>
</property>
<property name="resourceDirectoryLocations">
<list>
<value>classpath:net/shopin/bean/product</value>
</list>
</property>
</bean>
<bean id="jpaGpsDevice"
class="org.compass.gps.device.jpa.JpaGpsDevice">
<property name="name">
<value>JpaGpsDevice</value>
</property>
<property name="entityManagerFactory"
ref="entityManagerFactory" />
<property name="mirrorDataChanges">
<value>true</value>
</property>
</bean>
<!-- 数据库中的数据变化后同步更新索引 -->
<bean id="compassGps" class="org.compass.gps.impl.SingleCompassGps"
init-method="start" destroy-method="stop">
<property name="compass" ref="compass" />
<property name="gpsDevices">
<list>
<bean
class="org.compass.spring.device.SpringSyncTransactionGpsDeviceWrapper">
<property name="gpsDevice" ref="jpaGpsDevice" />
</bean>
</list>
</property>
</bean>
<bean id="compassTemplate"
class="org.compass.core.CompassTemplate">
<property name="compass" ref="compass" />
</bean>
<!-- 定时重建索引(利用quartz)或随Spring ApplicationContext启动而重建索引 -->
<bean id="compassIndexBuilder"
class="net.shopin.service.search.impl.CompassIndexBuilder"
lazy-init="false">
<property name="compassGps" ref="compassGps" />
<property name="buildIndex" value="true" />
<property name="lazyTime" value="5" />
</bean>
3.自动建立索引的java bean
Java代码
1.
2./**
3. * 通过quartz定时调度定时重建索引或自动随Spring ApplicationContext启动而重建索引的Builder.
4. * 会启动后延时数秒新开线程调用compassGps.index()函数.
5. * 默认会在Web应用每次启动时重建索引,可以设置buildIndex属性为false来禁止此功能.
6. * 也可以不用本Builder, 编写手动调用compassGps.index()的代码.
7. *
8. */
9.public class CompassIndexBuilder implements InitializingBean {
10. // 是否需要建立索引,可被设置为false使本Builder失效.
11. private boolean buildIndex = false;
12.
13. // 索引操作线程延时启动的时间,单位为秒
14. private int lazyTime = 10;
15.
16. // Compass封装
17. private CompassGps compassGps;
18.
19. // 索引线程
20. private Thread indexThread = new Thread() {
21.
22. @Override
23. public void run() {
24. try {
25. Thread.sleep(lazyTime * 1000);
26. System.out.println("begin compass index...");
27. long beginTime = System.currentTimeMillis();
28. // 重建索引.
29. // 如果compass实体中定义的索引文件已存在,索引过程中会建立临时索引,
30. // 索引完成后再进行覆盖.
31. compassGps.index();
32. long costTime = System.currentTimeMillis() - beginTime;
33. System.out.println("compss index finished.");
34. System.out.println("costed " + costTime + " milliseconds");
35. } catch (InterruptedException e) {
36. e.printStackTrace();
37. }
38. }
39. };
40.
41. /**
42. * 实现<code>InitializingBean</code>接口,在完成注入后调用启动索引线程.
43. *
44. * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
45. */
46. public void afterPropertiesSet() throws Exception {
47. if (buildIndex) {
48. indexThread.setDaemon(true);
49. indexThread.setName("Compass Indexer");
50. indexThread.start();
51. }
52. }
53.
54. public void setBuildIndex(boolean buildIndex) {
55. this.buildIndex = buildIndex;
56. }
57.
58. public void setLazyTime(int lazyTime) {
59. this.lazyTime = lazyTime;
60. }
61.
62. public void setCompassGps(CompassGps compassGps) {
63. this.compassGps = compassGps;
64. }
65.}
/**
* 通过quartz定时调度定时重建索引或自动随Spring ApplicationContext启动而重建索引的Builder.
* 会启动后延时数秒新开线程调用compassGps.index()函数.
* 默认会在Web应用每次启动时重建索引,可以设置buildIndex属性为false来禁止此功能.
* 也可以不用本Builder, 编写手动调用compassGps.index()的代码.
*
*/
public class CompassIndexBuilder implements InitializingBean {
// 是否需要建立索引,可被设置为false使本Builder失效.
private boolean buildIndex = false;
// 索引操作线程延时启动的时间,单位为秒
private int lazyTime = 10;
// Compass封装
private CompassGps compassGps;
// 索引线程
private Thread indexThread = new Thread() {
@Override
public void run() {
try {
Thread.sleep(lazyTime * 1000);
System.out.println("begin compass index...");
long beginTime = System.currentTimeMillis();
// 重建索引.
// 如果compass实体中定义的索引文件已存在,索引过程中会建立临时索引,
// 索引完成后再进行覆盖.
compassGps.index();
long costTime = System.currentTimeMillis() - beginTime;
System.out.println("compss index finished.");
System.out.println("costed " + costTime + " milliseconds");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
/**
* 实现<code>InitializingBean</code>接口,在完成注入后调用启动索引线程.
*
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/
public void afterPropertiesSet() throws Exception {
if (buildIndex) {
indexThread.setDaemon(true);
indexThread.setName("Compass Indexer");
indexThread.start();
}
}
public void setBuildIndex(boolean buildIndex) {
this.buildIndex = buildIndex;
}
public void setLazyTime(int lazyTime) {
this.lazyTime = lazyTime;
}
public void setCompassGps(CompassGps compassGps) {
this.compassGps = compassGps;
}
}
4.建立索引Service 层代码
Java代码
1.
2.@Service
3.@Transactional
4.public class SearchServiceBean extends DaoSupport implements SearchService {
5. @Resource(name = "compass")
6. Compass compass;
7.
8./** 创建索引 **/
9.public void index(ProductInfo p) {
10.
11.CompassSession session = compass.openSession();
12.CompassTransaction tx = null;
13.try {
14. tx = session.beginTransaction();
15. session.create(p);
16. tx.commit();
17.} catch (Exception e) {
18. if (tx != null) {
19.tx.commit();
20. }
21. throw new RuntimeException(e);
22. } finally {
23. if (session != null) {
24. session.close();
25. }
26. }
27. }
28. /** 删除一条索引 **/
29. public void delete(ProductInfo p) {
30. CompassTemplate ct = new CompassTemplate(compass);
31. ct.delete(p);
32. }
33. /** 更新(重新创建)一条索引 **/
34. public void update(final ProductInfo p) {
35. CompassTemplate ct = new CompassTemplate(compass);
36.
37. CompassCallback<Object> action = new CompassCallback<Object>() {
38.
39. public Object doInCompass(CompassSession session)
40. throws CompassException {
41. session.delete(p);
42. session.create(p);
43. return null;
44. }
45.
46. };
47.
48. ct.execute(action);
49. }
50. /** 索引查询 **/
51. public List<ProductInfo> find(final String keywords) {
52. CompassTemplate ct = new CompassTemplate(compass);
53. return ct.execute(new CompassCallback<List<ProductInfo>>() {
54.
55. public List<ProductInfo> doInCompass(CompassSession session)
56. throws CompassException {
57. List<ProductInfo> result = new ArrayList<ProductInfo>();
58. CompassQueryBuilder queryBuilder = session.queryBuilder();
59. CompassHits hits = null; // session.find(query);
60. /** 在所有字段中查询 **/
61. CompassQuery allPropertyQuery = queryBuilder.queryString(keywords).toQuery();
62. hits = allPropertyQuery.hits();
63. /** 在指定字段中查询 **/
64. // CompassQuery query = queryBuilder.term("name", keywords);
65. // hits = query.hits();
66. /** 指定范围查询 **/
67.// CompassQuery dateRangeQuery =
68.// queryBuilder.between("postTime",startTime, endTime, true);
69.// hits = queryBuilder.bool()
70.// .addMust(allPropertyQuery)
71.// .addMust(dateRangeQuery)
72.// .toQuery()
73.// .hits();
74.// System.out.println("---------");
75. for (int i = 0; i < hits.length(); i++) {
76. ProductInfo p = (ProductInfo) hits.data(i);
77. /** 如果进行高亮的属性中没有出现关键字, 则返回null **/
78.// String ht = hits.highlighter(i).fragment("name");
79.// if (ht != null) {
80.// p.setName(ht);
81.// }
82.// String hc = hits.highlighter(i).fragment("code");
83.// if (hc != null) {
84.// p.setCode(hc);
85.// }
86. result.add(p);
87. }
88. return result;
89. }
90. });
91. }
@Service
@Transactional
public class SearchServiceBean extends DaoSupport implements SearchService {
@Resource(name = "compass")
Compass compass;
/** 创建索引 **/
public void index(ProductInfo p) {
CompassSession session = compass.openSession();
CompassTransaction tx = null;
try {
tx = session.beginTransaction();
session.create(p);
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.commit();
}
throw new RuntimeException(e);
} finally {
if (session != null) {
session.close();
}
}
}
/** 删除一条索引 **/
public void delete(ProductInfo p) {
CompassTemplate ct = new CompassTemplate(compass);
ct.delete(p);
}
/** 更新(重新创建)一条索引 **/
public void update(final ProductInfo p) {
CompassTemplate ct = new CompassTemplate(compass);
CompassCallback<Object> action = new CompassCallback<Object>() {
public Object doInCompass(CompassSession session)
throws CompassException {
session.delete(p);
session.create(p);
return null;
}
};
ct.execute(action);
}
/** 索引查询 **/
public List<ProductInfo> find(final String keywords) {
CompassTemplate ct = new CompassTemplate(compass);
return ct.execute(new CompassCallback<List<ProductInfo>>() {
public List<ProductInfo> doInCompass(CompassSession session)
throws CompassException {
List<ProductInfo> result = new ArrayList<ProductInfo>();
CompassQueryBuilder queryBuilder = session.queryBuilder();
CompassHits hits = null; // session.find(query);
/** 在所有字段中查询 **/
CompassQuery allPropertyQuery = queryBuilder.queryString(keywords).toQuery();
hits = allPropertyQuery.hits();
/** 在指定字段中查询 **/
// CompassQuery query = queryBuilder.term("name", keywords);
// hits = query.hits();
/** 指定范围查询 **/
// CompassQuery dateRangeQuery =
// queryBuilder.between("postTime",startTime, endTime, true);
// hits = queryBuilder.bool()
// .addMust(allPropertyQuery)
// .addMust(dateRangeQuery)
// .toQuery()
// .hits();
// System.out.println("---------");
for (int i = 0; i < hits.length(); i++) {
ProductInfo p = (ProductInfo) hits.data(i);
/** 如果进行高亮的属性中没有出现关键字, 则返回null **/
// String ht = hits.highlighter(i).fragment("name");
// if (ht != null) {
// p.setName(ht);
// }
// String hc = hits.highlighter(i).fragment("code");
// if (hc != null) {
// p.setCode(hc);
// }
result.add(p);
}
return result;
}
});
}
控制层
Java代码
1.@Controller("/search/gosearch")
2.public class SearchAction extends Action {
3. @Resource(name = "searchServiceBean")
4. private SearchService SearchService;
5.
6. @Override
7. public ActionForward execute(ActionMapping mapping, ActionForm form,
8. HttpServletRequest request, HttpServletResponse response)
9. throws Exception {
10. String keywords=request.getParameter("word").trim();
11. if(keywords==null||"".equals(keywords)){
12. return mapping.findForward("noproduct");
13. }
14. System.out.println("------"+keywords);
15. List<ProductInfo> list = SearchService.find(keywords);
16. request.setAttribute("word", keywords);
17. request.setAttribute("product",list);
18. if(list.isEmpty()){
19. return mapping.findForward("noproduct");
20. }else{
21. return mapping.findForward("list");
22.
23. }
24. }
25.}
@Controller("/search/gosearch")
public class SearchAction extends Action {
@Resource(name = "searchServiceBean")
private SearchService SearchService;
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String keywords=request.getParameter("word").trim();
if(keywords==null||"".equals(keywords)){
return mapping.findForward("noproduct");
}
System.out.println("------"+keywords);
List<ProductInfo> list = SearchService.find(keywords);
request.setAttribute("word", keywords);
request.setAttribute("product",list);
if(list.isEmpty()){
return mapping.findForward("noproduct");
}else{
return mapping.findForward("list");
}
}
}
junit测试
Java代码
1.public class SearchTest {
2.
3. private static AbstractApplicationContext context;
4. @BeforeClass
5. public static void setUpBeforeClass() throws Exception {
6. try {
7. context = new ClassPathXmlApplicationContext("beans.xml");
8. } catch (Exception e) {
9. e.printStackTrace();
10. }
11. }
12.
13. @Test
14. public void testDelete() {
15. SearchService searchService = (SearchService) context
16. .getBean("searchServiceBean");
17. ProductInfo p = new ProductInfo(2);
18. searchService.delete(p);
19. }
20.
21. @Test
22. public void createIndex(){
23. SearchService searchService = (SearchService) context
24. .getBean("searchServiceBean");
25. ProductInfoService productInfoService = (ProductInfoService) context
26. .getBean("productInfoServiceBean");
27. List<ProductInfo> list=productInfoService.getAllProduct();
28. for(ProductInfo productInfo:list){
29.// System.out.println("-------"+productInfo.getName());
30. searchService.index(productInfo);
31. }
32. }
33.
34. @Test
35. public void testSearch() {
36. SearchService searchService = (SearchService) context
37. .getBean("searchServiceBean");
38. String query = "手机";
39. List<ProductInfo> ProductInfos;
40.
41. ProductInfos = searchService.find(query);
42. for (ProductInfo p : ProductInfos) {
43. System.out.println(p.getName());
44. }
45. System.out.println("------------");
46. }
47.}
发表评论
-
compass问题
2010-06-03 13:54 0应用中用到了compass+spring+hibernate. ... -
Compass---Search Engine (1)
2010-03-29 16:32 0Compass核心提供了一个 ... -
compass 配置
2010-03-29 15:51 0<bean id="compass" ... -
compass学习笔记
2010-02-20 16:53 1842Compass概念: 1:Compass相 ... -
如何配置compass的索引位置为相对路径
2009-12-24 15:33 1582Compass是对lucene进行封装的java项目,使得在s ... -
Compass2.0.2版本自带例子分析
2009-12-17 14:09 1574下面的代码来自compass自带的例子,我稍微改造了一下。 ... -
ssh与compass结合的例子
2009-11-30 11:27 2035SSH把compass加进来是要加5个jar, comp ...
相关推荐
通过使用Compass 2.2.0,开发者可以在Java应用中轻松集成搜索引擎功能,提升用户体验,同时减少维护成本。在实际项目中,我们可以根据需求选择合适的Compass配置,结合其提供的工具和API,实现高效的全文搜索、数据...
Compass 提供了对 ORM 框架(如 Hibernate)的集成,使得数据库中的数据可以被索引并用于搜索。 **2. Hibernate:** Hibernate 是一个流行的 Java ORM(对象关系映射)框架,它简化了数据库操作,使开发者可以使用...
Compass 是一个基于 Lucene 的 Java 搜索引擎框架,旨在提供一种简单、高效的方式来索引和搜索对象。它支持多种数据存储方式,并能够与 Spring 框架无缝集成。此文档为 Compass 2.1.0 版本的参考手册,详细介绍了...
该框架支持多种搜索引擎(如Elasticsearch, Solr等),使得开发人员能够在不深入学习特定搜索引擎的情况下,轻松地在其应用中集成高级的全文搜索功能。 #### 二、项目模型定义 在本文档的第一部分,展示了`...
标题 "Spring ,JPA,Compass使用注解开发的博客站内搜索" 涉及的是在Java开发环境中,利用Spring框架、Java Persistence API (JPA) 和 Compass搜索引擎来实现一个博客系统的站内搜索功能。这是一项关键的技术,因为...
标题中的"S2SH+compass"指的是一个基于Struts2(S),Spring(S)和Hibernate(H)这三种开源框架的Java Web应用,再加上Compass搜索引擎来实现站内全文检索的功能。这种组合常用于构建复杂的企业级应用,因为它提供...
通过以上步骤,你可以在SSH框架下成功集成Compass实现站内搜索分页。这一过程涉及到Java Web开发的多个层面,包括MVC架构、数据库操作、全文检索以及用户体验设计。熟练掌握这些技能将有助于构建高效且功能丰富的Web...
Compass是一个高性能的开源Java搜索引擎框架,旨在简化应用程序与搜索引擎之间的集成过程。它不仅利用了顶级的Lucene搜索引擎的强大功能,还融合了诸如Hibernate和Spring等流行框架的优势,从而为开发者提供了一个...
要将Compass集成到Java项目中,除了下载JAR包外,还需要配置Compass环境。这通常包括设置Compass的配置文件(如`compass.cfg.xml`),以及定义索引和搜索策略等。具体配置项取决于项目的需求,例如索引存储位置、...
Compass基于Lucene之上,类似于Hibernate之于JDBC的关系,提供了更高层次的封装,使得开发者能够更容易地集成搜索引擎到Java应用程序中。 - **OSEM**:OSEM (Object Search Engine Mapping) 是Compass提供的一个...
标题中的“compass+ssh2集成 hibernategps问题”指的是在Java开发中,开发者尝试将Compass搜索引擎库与SSH2(Spring、Struts和Hibernate)框架整合时遇到的问题,特别是与Hibernate的GPS(Global Persistent ...
【compass完整可用项目】是一个基于特定技术栈的软件开发项目,该项目的核心是Compass库,一个与Lucene紧密集成的全文搜索引擎工具。Compass提供了一种简单的方式来在Java应用程序中集成全文搜索功能,使得开发者...
Compass搜索引擎技术是一种基于Lucene的全文检索框架,它提供了更高级别的API和集成机制,使得在Java应用程序中实现搜索引擎功能变得更加便捷。Compass的主要目标是将全文索引能力无缝地融入到现有的业务应用程序中...
Compass是一款基于Apache Lucene的全文搜索引擎框架,它为开发者提供了更高级别的抽象层,简化了搜索引擎的集成工作。在理解Compass之前,我们需要先了解全文检索的基本概念和原理。 全文检索是相对于传统的基于...
Compass对象搜索引擎是一款基于Lucene的全文搜索引擎框架,它为Java开发者提供了高级的搜索功能,使得在应用程序中集成全文检索变得更加便捷。Compass的核心理念是将数据库中的对象与Lucene索引之间建立映射...
Compass不仅支持对关系数据库中的数据进行索引,还能与ORM框架如Hibernate、JPA等无缝集成,使得索引和搜索的数据可以与业务数据保持一致。 **二、Compass的核心特性** 1. **ORM集成**:Compass能够自动跟踪和更新...
在Java应用中集成搜索引擎功能时,Compass提供了一种简化的方式来管理和操作Lucene索引。通过Compass,你可以将对象-关系映射(ORM)与全文检索完美结合,使得数据库中的数据能够被快速高效地搜索。 **Compass的...