我正在尝试制作一个迷你应用程序,类似于公告板。我似乎无法让它通过过滤器进行搜索。我试过了CriteriaBuilder,它没有弄清楚那里有什么以及为什么。然后我决定通过创建对数据库的动态查询来进行过滤。数据库Oracle。实体Ad- 声明:
@Entity
@Table(name = "AD")
public class Ad extends IdEntity{
private Long id;
private User user;
private String name;
private String description;
private Integer price;
private String city;
private String numberPhone;
private Date dateFrom;
private Date dateTo;
private CurrencyType currencyType;
private CategoryType categoryType;
private SubcategoryType subcategoryType;
public Ad() {
}
@Id
@SequenceGenerator(name = "AD_SQ", sequenceName = "AD_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AD_SQ")
@Column(name = "ID_AD")
@Override
public Long getId() {
return id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ID_USER")
public User getUser() {
return user;
}
@Column(name = "AD_NAME", nullable = false)
public String getName() {
return name;
}
@Column(name = "AD_DESCRIPTION", nullable = false)
public String getDescription() {
return description;
}
@Column(name = "PRICE", nullable = false)
public Integer getPrice() {
return price;
}
@Column(name = "CITY", nullable = false)
public String getCity() {
return city;
}
@Column(name = "NUMBER_PHONE", nullable = false)
public String getNumberPhone() {
return numberPhone;
}
@Column(name = "DATE_FROM", nullable = false)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy'T'hh:mm")
public Date getDateFrom() {
return dateFrom;
}
@Column(name = "DATE_TO", nullable = false)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy'T'hh:mm")
public Date getDateTo() {
return dateTo;
}
@Enumerated(EnumType.STRING)
@Column(name = "CURRENCY_TYPE", nullable = false)
public CurrencyType getCurrencyType() {
return currencyType;
}
@Enumerated(EnumType.STRING)
@Column(name = "CATEGORY_TYPE", nullable = false)
public CategoryType getCategoryType() {
return categoryType;
}
@Enumerated(EnumType.STRING)
@Column(name = "SUBCATEGORY_TYPE", nullable = false)
public SubcategoryType getSubcategoryType() {
return subcategoryType;
}
@JsonCreator
public static Ad createFromJson(String jsonString){
ObjectMapper objectMapper = new ObjectMapper();
Ad ad = null;
try {
ad = objectMapper.readValue(jsonString, Ad.class);
}catch (IOException e){
e.printStackTrace();
}
return ad;
//getters and setters, equals and hash code
//I don’t give this data, but they exist
}
Filter:
public class Filter {
private CategoryType categoryType;
private String city;
private String description;
public Filter() {
}
public CategoryType getCategoryType() {
return categoryType;
}
public void setCategory(CategoryType categoryType) {
this.categoryType = categoryType;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@JsonCreator
public static Filter createFromJson(String jsonString){
ObjectMapper objectMapper = new ObjectMapper();
Filter filter = null;
try {
filter = objectMapper.readValue(jsonString, Filter.class);
}catch (IOException e){
e.printStackTrace();
}
return filter;
}
@Override
public String toString() {
return new StringJoiner(", ", Filter.class.getSimpleName() + "[", "]")
.add("categoryType=" + categoryType)
.add("city='" + city + "'")
.add("description='" + description + "'")
.toString();
}
}
类AdDAO:
@Repository("adDAO")
@Transactional
public class AdDAO extends GeneralDAO<Ad> {
@SuppressWarnings("SqlResolve")
private static final String SQL_GET_ADS_BY_CURRENT_DATE = "SELECT * FROM AD WHERE ROWNUM < 101 AND DATE_TO > ? ORDER BY DATE_TO DESC";
private static final String SQL_GET_ADS_BY_FILTER = "SELECT * FROM AD WHERE ROWNUM < 101 AND DATE_TO > ? AND AD_DESCRIPTION LIKE ?";
//1. получить текущую дату
//2. сравнить в запросе текущую дату с датой объекта
//3. если дата объекта меньше текущей даты то взять этот объект из базы данных
//4. выводить только 100 последних объектов удовлетворяющих условию по дате
@SuppressWarnings("unchecked")
public List<Ad> get100Ad(){
Date currentDate = new Date();
NativeQuery<Ad> query = (NativeQuery<Ad>) getEntityManager().createNativeQuery(SQL_GET_ADS_BY_CURRENT_DATE, Ad.class);
return query.setParameter(1, currentDate, TemporalType.TIMESTAMP).getResultList();
}
@SuppressWarnings("unchecked")
public List<Ad> findAds(Filter filter){
Date currentDate = new Date();
String findByWord = filter.getDescription();
System.out.println("FindByWord " + findByWord);
NativeQuery<Ad> adQuery = (NativeQuery<Ad>) getEntityManager().createNativeQuery(createQuery(filter), Ad.class);
adQuery.setParameter(2, "%'" + findByWord + "'%");
adQuery.setParameter(1, currentDate, TemporalType.TIMESTAMP);
return adQuery.getResultList();
}
private String createQuery(Filter filter){
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(SQL_GET_ADS_BY_FILTER);
if (filter.getCategoryType() != null){
stringBuilder.append(" AND CATEGORY_TYPE = '").append(filter.getCategoryType().toString()).append("'");
}
if (filter.getCity() != null){
stringBuilder.append(" AND CITY = '").append(filter.getCity()).append("'");
}
return stringBuilder.append(" ORDER BY DATE_TO DESC").toString();
}
}
获取最后一百个广告的方法get100Ad(),考虑到日期,工作并返回找到的广告。并且该方法findAds(Filter filter)不断返回一个空列表,尽管数据库中有满足请求的对象。告诉我出了什么事?我的错误或错误是什么?
尝试明确指定名称
并将选项更改为(不带
')并启用(类似
log4j.logger.org.hibernate.SQL=debug)或添加额外的日志记录以查看哪些请求实际进入数据库