spring data native query interesting bug with Lob column - java

I have an entity:
#Entity public class KnowledgeBase {
private Long id;
private String link;
private String content;
#Id
#SequenceGenerator(name = "knowledgebase_id_generator", sequenceName = "knowledgebase_id_sequence", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "knowledgebase_id_generator")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
And I have a spring data repository
#Repository public interface KnowledgeBaseRepository
extends AbstractRepository<KnowledgeBase, Long> {
#Query(value = "SELECT c.id as id,c.link as link, c.content as content"
+ " from knowledgebase c where content=?1", nativeQuery = true)
List<KnowledgeBase> findRelevantRecords(String searchString);
}
Please note that
where content=?1
is just a sample, where clause was different for testing.
The issue is if I run this repository method, everything just fine, but content column contains large text amount, I want it to be lazy loaded. If I do that I get error that value is wrong for Long: ''. So my entity is:
#Lob #Basic(fetch = LAZY) String content;
If I remove this, everything just fine.
How to prevent content column from being loaded every time and have spring data repository search properly?

try this:
Create a constructor in your entity which accepts only the required fields
public class KnowledgeBase{
//default constructor
public KnowledgeBase(){}
public KnowledgeBase(Long id,String link){
this.id=id;
this.link=link;
}
}
and use this constructor signature in your query in your repository
#Query(value = "SELECT new #{#entityName} (c.id as id,c.link as link) from #{#entityName} c "
+ " from knowledgebase c where content=?1", nativeQuery = true)
List<KnowledgeBase> findRelevantRecordsWithoutContent(String searchString);

Related

Hibernate query returns null, but entity gets loaded on object anyway

This will take some explaining. So, I have an entity called Invoice and a related table called Errors, which is used to store some processing errors.
In a DAO class, I have a query for fetch the errors with some specific criteria:
public Errors loadLastError(Invoice i) {
try (Session session = factory.openSession()) {
Query query = session.createQuery("select er from Errors er" +
" inner join er.invoice i" +
" where er.invoice = :invoice" +
" and i.status <> :code" +
" and i.proccessStatus = :status" +
" order by er.id desc");
query.setParameter("invoice", invoice);
query.setParameter("code", "001");
query.setParameter("status", "form_error");
var result = query.getSingleResult();
return (Errors) result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
This works fine: will only get results when the conditions match. When they don't, I get the expected null result where this method is called:
this.invoice.setError(loadLastError(this.invoice);
When inspecting the code, I can see that the this.invoice object was updated correctly with a null result.
But, as soon as I pass this object invoice to another class in order to do some proccessing (send notifications basically by JSON), it gets there with a Errors object loaded, as if my original query had actually found something, which it didn't.
The following are a shortened example of my entity classes:
The Invoice:
#Entity
#DynamicUpdate
#Table(name = "data.invoice")
#TypeDef(
name = "pgsql_enum",
typeClass = PostgreSQLEnumType.class
)
public class Invoice implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#JsonIgnore
#Column(name = "proccessStatus")
private String proccessStatus;
#JsonIgnore
#Column(name = "status")
private String status;
#JsonIgnore
#OneToOne(mappedBy = "invoice", fetch = FetchType.LAZY)
private Errors errors;
public Integer getId() {
return id;
}
public String getProccessStatus() {
return proccessStatus;
}
public void setProccessStatus(String proccessStatus) {
this.proccessStatus= proccessStatus;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status= status;
}
public Errors getErrosr() {
return errors;
}
public void setErrors(Errorserrors) {
this.errors= errors;
}
The Errors entity:
#Entity
#Table(name = "data.invoice_errors")
public class Errors implements Serializable {
public Errors() {
}
public Errors(Invoice invoice, String error) {
this.invoice= invoice;
this.error = error;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#OneToOne
#JoinColumn(name = "id_invoice")
private Invoice invoice;
private String error;
#Column(name = "created_at")
private LocalDateTime createdAt;
public Integer getId() {
return id;
}
public Invoice getInvoice() {
return invoice;
}
public void setInvoice(Invoice invoice) {
this.invoice = invoice;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
This behaviour seems very strange and I don't know how to diagnose it and what may be wrong. Any input would be very appreciated.
What I'm expecting is that the entity don't get updated out of nowhere with a result that wasn't found initially because it simply didn't match the search criteria in the first place.
I'm a colossal idiot. The issue was that the notification class was refreshing the model. Changed the database search to go after the refresh and fixed the problem.

JPA createQuery where condition does not work

I am trying to use JPA to fetch records from database. However I am able to insert records indatabse and even get all the records using createQuery method of class EntityManager.
But in below case I am not getting why the condition in where clause is not working.
Please help me figure it out.
POJO class :
#Entity
#Table(name = "frameworks_filter")
public class FilteredFrameworksDbStructure {
#Id
#Column(name="id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "regular_name")
private String regularName;
#Column(name = "component_name")
private String componentName;
#Column(name = "component_owner")
private String componentOwner;
#Column(name = "frameworks")
private String frameworks;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRegularName() {
return regularName;
}
public void setRegularName(String regularName) {
this.regularName = regularName;
}
public String getComponentName() {
return componentName;
}
public void setComponentName(String componentName) {
this.componentName = componentName;
}
public String getComponentOwner() {
return componentOwner;
}
public void setComponentOwner(String componentOwner) {
this.componentOwner = componentOwner;
}
public String getFrameworks() {
return frameworks;
}
public void setFrameworks(String frameworks) {
this.frameworks = frameworks;
}
}
DAO class method:
public List<FilteredFrameworksDbStructure> getFilteredFrameworks(String regularName) {
EntityManager entityManager = entityManagerFactory.createEntityManager();
List<FilteredFrameworksDbStructure> filteredFrameworksDbStructureList = entityManager
.createQuery("from FilteredFrameworksDbStructure F where F.regularName = :regular", FilteredFrameworksDbStructure.class)
.setParameter("regular", regularName)
.getResultList();
return filteredFrameworksDbStructureList;
}
Issue : Condition in where clause does not work. It simply fetch all the records irrespective of the regularName provided.
Regards,
Parag Vinchurkar
Why don't you use the JpaRepository or CrudRepository to fetch your results? Check out this tutorial here and here on how to use them.
And you can use your where clause. Please see below the example repository you can use to obtain the same results as the entityManager
public interface FilteredFrameworksDbStructureRepo extends JpaRepository<FilteredFrameworksDbStructure , Integer>{
List<FilteredFrameworksDbStructure> findAllByRegularName(String regularName)
}
Please note that you will have to change your id member variable from int to Integer

Dynamically Query from List or two different entities

I have an entity called Person, inside that basic metadata, then inside that Tag and Language. I want to get all rows that contain specific tag name and language.
I came to know about Criteria Query about. How can we interlink two different entities together?
Example: Get all rows having the tag as Model and language as English.
#Entity
public Person {
#Id
private String id;
private BasicMetadata basicMetadata;
-----------
}
Basic Metadata table
#Entity
public BasicMetadata {
#Id
private String id;
private List<Tag> tags;
private List<Language> language;
-------------
}
Tag Table
#Entity
public Tag {
#Id
private String id;
private String name;
-------------
}
Language Table
#Entity
public Language{
#Id
private String id;
private String name;
-------------
}
I created a simple method for specification Query is that correct
private Specification<Person> containsText(String keyword) {
return (root,query, builder) -> {
String finalText = keyword.toLowerCase();
if (!finalText.contains("%")) {
finalText = "%" + finalText + "%";
}
Predicate genreExp = builder.like(builder.lower(root.get("basicMetadata").get("tags")), finalText);
return builder.or(genreExp);
};
you can write your specification like this
public class PersonSpecifications {
public static Specification<Person> hasTag(String keyword) {
return (root, query, builder) -> {
String finalText = keyword.toLowerCase();
if (!finalText.contains("%")) {
finalText = "%" + finalText + "%";
}
Join<Person, BasicMetaData> md = root.join("basicMetaData");
return builder.like(builder.lower(md.join("tags").get("name")), finalText);
}
}
}
and you can use this specification to get the filtered results like this
repository.findAll(PersonSpecifications. hasTag("abc"),PageRequest,of(0,10));

Using SQL-IN-clause in custom #Query in JPA-/CrudRepository with the list or set as passed parameter?

Hi Spring and Hibernate experts!
Can any one say if it is possible to use SQL IN-clause in custom #Query in CrudRepository while the Arraylist or set of strings is passed as parameter?
I am relatively new to Spring and do not quite figure out why I get the following Spring error:
"java.lang.IllegalArgumentException: Parameter value [d9a873ed-3f15-4af5-ab1b-9486017e5611] did not match expected type [IoTlite.model.Device (n/a)]"
In this post (JPQL IN clause: Java-Arrays (or Lists, Sets...)?) the subject is discussed pretty closely but I cannot make the suggested solution to work in my case with custom #Query.
My demo repository as part of the spring boot restful application is the following:
#Repository
public interface DeviceRepository extends JpaRepository<Device, Long> {
#Query("SELECT d FROM Device d WHERE d IN (:uuid)")
List<Device> fetchUuids(#Param("uuid") Set<String> uuid);
}
And the model-class is the following:
#Entity
#SequenceGenerator(sequenceName = "device_seq", name = "device_seq_gen", allocationSize = 1)
#JsonIgnoreProperties(ignoreUnknown = true)
public class Device implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "device_seq_gen")
#JsonIgnore
private Integer id;
#Column(unique=true, length=36)
#NotNull
private String uuid = UUID.randomUUID().toString();
#Column(name="name")
private String name;
#JsonInclude(JsonInclude.Include.NON_NULL)
private String description;
#OneToMany(
mappedBy="device",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<Sensor> sensors = new ArrayList<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#JsonIgnore
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDeviceUuid() {
return uuid;
}
public void setDeviceUuid(String deviceUuid) {
this.uuid = deviceUuid;
}
public List<Sensor> getSensors() {
return sensors;
}
public void addSensor(Sensor sensor){
sensor.setDevice(this);
sensors.add(sensor);
}
}
An here is the relevant part of the service calling the fetchUuids-custom-method with set-list of strings as parameter (service naturally being called by the relevant restcontroller):
#Service
public class DeviceService implements IDeviceService {
#Autowired
private DeviceRepository deviceRepository;
...
#Override
public List<Device> listDevices(Set<String> clientIds) {
return deviceRepository.fetchUuids(clientIds);
}
...
}
Quick fix
You have WHERE d IN (:uuid) in the custom query. You cannot match d, which is an alias for Device entity with :uuid parameter, which is a collection of Strings.
WHERE d.uuid IN (:uuid) would fix the query - it matches a String with Strings.
What you should do instead
It's rather misleading to name the method fetchUuids and return a list of Device instances. It's also unnecessary to write a custom query to do that. You can benefor from repository method name conventions and let Spring Data Jpa framework generate the query for you:
List<Device> findByUuidIn(Set<String> uuids);
You can write in this way
#Query(value = "select name from teams where name in :names", nativeQuery = true)
List<String> getNames(#Param("names") String[] names);
and call the function in service and pass an array of String as arguments.like this
String[] names = {"testing team","development team"};
List<String> teamtest = teamRepository.getNames(names);
Yes is possible to using collection in JPA query parameters.
Your query is wrong, it should be like this:
#Query("SELECT d FROM Device d WHERE d.uuid IN :uuid")

Getting Next value from sequence with spring hibernate

I am using spring jpa repository with hibernate to save entites to my oracle database. How I can get the next value of my oracle database sequence using Spring-Hibernate?
This is my Event class :
#Entity
public class Event {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Long seriesId;
private String description;
public Event() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getSeriesId() {
return seriesId;
}
public void setSeriesId(Long seriesId) {
this.seriesId = seriesId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
I need to get the next value of the sequence once for the all event series in the event resolver.
public class EventResolver {
#Autowired
private EventRepository eventRepository;
public void createSeriesOfEvents(List<EventAPI> eventsToCreate){
Long seriesId = null; // TODO: Get the series id from database sequence
for (EventAPI currEvent : eventsToCreate){
Event newEvent = new Event();
newEvent.setDescription(currEvent.description);
newEvent.setSeriesId(seriesId);
eventRepository.save(newEvent);
}
}
}
Thanks for any kind of help..
Finally I Solved my problem in the Spring way, All you need is to add a native query in the JpaRepository like this:
public interface EventRepository extends JpaRepository<Event, Long> {
#Query(value = "SELECT seq_name.nextval FROM dual", nativeQuery =
true)
Long getNextSeriesId();
With Spring 5, you can use one of their built-in classes for this task like OracleSequenceMaxValueIncrementer
See all the available options in this package: https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/support/incrementer/package-summary.html
Annotate your id property like so:
#Id
#GeneratedValue(generator = "idSequence")
#SequenceGenerator(schema = "MYORASCHEMA", name = "idSequence", sequenceName = "MY_ORACLE_SEQ_NAME", allocationSize = 1)
#Column(name="ID")
private Long id;
You can use this approach in JPA:
Query q = em.createNativeQuery("select seq_name.nextval from dual");
return (Long)q.getSingleResult();

Categories

Resources