I have set of entity (POJO) classes, Each entity class will have one property stopDate , which is type of Date.
#Entity
#Table(name="ORG")
public class Organization extends PersistentObjImpl {
private Long odbid; //ODBID NUMBER(11) i.e. Primary Key
private String actionFeedReqInd;
private String alternateName;
private Date stopDate; //STOP_DATE NOT NULL DATE
#Temporal(TemporalType.DATE)
#Column(name="STOP_DATE", nullable=false)
public Date getStopDate() {
return stopDate;
}
public void setStopDate(Date stopDate) {
this.stopDate = stopDate;
}
//setter and getter methods for corresponding columns i.e. properties
}
in Organization Database table, if any row's stop_date column value is less than current date(sysdate) , we should not fetch those rows using Hibernate.
Ex: Org data base table.
ODBID Column1 Column2 stop_date
1 - - 2015-02-13
2 - - 2010-04-23
3 - - 2009-03-13
Here is the SQL statement and Output ,which I am expecting.
SELECT ODBID, , from ORG WHERE stop_date>sysdate ;
ODBID Column1 Column2 stop_date
1 - - 2015-02-13
Like this , I have so many tables, which has stop_date as column, from any one of the table, if the stop_date < sysdate, i don't want to retrieve those records ..
I am not interested to write stop_date>sysdate condition in each SQL/HQL select query. Is there any way I can configure this condition once, and use in all the Entity (POJO ) classes.
Please provide me a generic way.
Related
I have an object which has jsonb column. Is there any way to query into this jsonb column using querydsl?
Here is an example of my objects:
public class Person {
#Type(type = "jsonb")
#Column(columnDefinition = "jsonb")
private PersonDocument personDocument;
}
public class PersonDocument {
private int documentType;
private List<DocumentDetail> documentDetails;
}
public class DocumentDetail {
private String country;
private String documentId;
private LocalDate expiryDate
}
I would like to search person by documentId, so I need to get to documentId column
QueryDSL doesn't have any support for queries on PostgreSQL jsonb column. I have one solution that works for Query on the PostgreSQL field using QueryDSL.
solution steps:
Create a database view using the table where jsonb column. The view uses to convert your jsonb to the table normal table structure. like table A(j jsonb) now you want the field "xyz" from "j" jsonb column from A table. you can apply the following query:
CREATE OR REPLACE VIEW view_b as select a.id as a_id,a->> "xyz" as xyz from A a
now, view table structure like view_b(a_id,xyz)
Now you create a domain object which represents this view.
#Table(name="view_b") public class ViewB{...}
now you can query using query DSL. like qViewB.xyz.eq("value")
I have a numeric(10,2) data type column named "Value" in a Payment table in postgresql Database.
CREATE TABLE IF NOT EXISTS PAYMENT(
PAYMENT_ID BIGINT NOT NULL DEFAULT nextval('payment_seq') PRIMARY KEY,
DATE TIMESTAMP,
PLACE VARCHAR(255),
VALUE NUMERIC(10,2) NOT NULL,
UTILISATEUR_ID BIGINT REFERENCES UTILISATEUR
);
I want to retrieve that numeric value by a BigDecimal Data Type in Java. (dto)
import java.math.BigDecimal;
public interface UserSumByGroup {
public String getFullName();
public BigDecimal getSumOfValues();
}
For some reason all the times the return values for the dto is null when I execute in the controller..
...
List<UserSumByGroup> usersGroupSumPaymnt = userRepo.userGroupSumPaymt();
model.addAttribute("userGroupListSumPaymt", usersGroupSumPaymnt);
System.out.println("usersGroupSumPaymnt=> "+usersGroupSumPaymnt.get(0).getSumOfValues());
...
SQL Query:
SELECT usr.FULL_NAME as fullName, SUM(VALUE) as paymentCount
FROM PAYMENT pym left join UTILISATEUR usr ON usr.utilisateur_id = pym.utilisateur_id
WHERE MONTH(pym.date) = MONTH(CURRENT_DATE)
AND YEAR(pym.date) = YEAR(CURRENT_DATE)
AND pym.utilisateur_id IN (1,5)
GROUP BY pym.utilisateur_id, usr.FULL_NAME;
Console Log:
usersGroupSumPaymnt=> null
Do you have some idea why I got always a Null?.
Thanks.
To correspond the names of the variables between Spring JPA and the Database, the names of the attributes of the dto object must be the same to the name of the result field in the query.
The name of the result query "paymentCount" needs to be the same as the dto instance "sumOfValues".
So, Change:
SUM(VALUE) as paymentCount
By
SUM(VALUE) as sumOfValues
I use Mybatis to access db, and some tables is sharding by id with hash algorithm.
I want to write a Mybatis intecepter to change table name automatic, it need to get the sharding column value.
Table Entity:
#Data
#TableName("m_user")
public class User {
#TableId(type = IdType.AUTO)
private Integer id;
private String name;
private Integer age;
}
UserMapper sql:
#Select("select * from m_user where id = #{id2} and name = #{name2};")
List<User> selectByIdAndName(Integer id2, String name2);
I use boundSql.getParameterObject() and boundSql.getParameterMappings() to check, but I can not make sure whether the sharding column id is in sql and then get the value of the sharding column.
ParameterMappings values and ParameterObject values are here:
parameter mapping:ParameterMapping{property='id2', mode=IN, javaType=class java.lang.Object, jdbcType=null, numericScale=null, resultMapId='null', jdbcTypeName='null', expression='null'}
parameter mapping:ParameterMapping{property='name2', mode=IN, javaType=class java.lang.Object, jdbcType=null, numericScale=null, resultMapId='null', jdbcTypeName='null', expression='null'}
params:{id2=1, param1=1, name2=name1, param2=name1}
The parameters are Mapper function parameters, but I need sharding column id and value, program can only get id2 or param1.
How to get the db column and value from Mybatis?
I'm getting this error:
Cannot insert the value NULL into column 'EntryDate', table 'eApps.Logs.dbo.Logs'; column does not allow nulls. INSERT fails.
I have a standard add function to EF 6
public Logs AddLog(Logs p)
{
Logs.Add(p);
SaveChanges();
return p;
}
I've defined the field in my class as:
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime EntryDate { get; set; }
Should I be populating this field in my controller at all?
Please note that column EntryDate in table does not allow NULL. Hence, you must ensure that object p got valid date. Other option could be to change table schema and modify EntryDate column to accept NULL.
I added a constraint on the EntryDate field in SQL Server to default this field to GETDATE()
Following is the table structure:
desc customer_survey
Name Null Type
----------- -------- ------------
SURVEYID NOT NULL VARCHAR2(10)
CUSTNO NOT NULL VARCHAR2(10)
SRNO NUMBER(10)
AVGRATINGS NUMBER(5,2)
COMMENTS VARCHAR2(50)
SENTON DATE
RESPONDEDON DATE
desc Survey_response
Name Null Type
---------------- -------- ------------
SURVEYRESPONSEID NOT NULL NUMBER(10)
RATINGS NOT NULL NUMBER(2)
QNO NOT NULL VARCHAR2(10)
SURVEYID NOT NULL VARCHAR2(10)
Java classes:
public class CustomerSurvey implements Serializable {
#OneToMany(fetch=FetchType.EAGER, mappedBy="customerSurvey",
cascade=CascadeType.ALL)
private Set<SurveyResponse> responses;
......
public class SurveyResponse {
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="SURVEYID", referencedColumnName="surveyId")
private CustomerSurvey customerSurvey;
......
Client code:
List<CustomerSurvey> surveys = workService.getSurveysByCustomer("testCNo2");
System.out.println("surveys size = " + surveys.size());
for(CustomerSurvey survey: surveys) {
System.out.println("getting responses from the survey object now..");
Set<SurveyResponse> responses = survey.getResponses();
System.out.println("responses size= .." + responses.size());
}
console shows:
surveys size = 1
getting responses from the survey object now..
responses size= ..0
whereas there are 7 responses in the DB for the selected survey.
Enable logging and look if the SQL is correct.
It is hard to tell from your incomplete code, but in general a OneToMany should not use a JoinColumn it should use a mappedBy, and the join column in the ManyToOne should reference the Id of the object.
Also ensure you are setting both sides of the relationship when you insert your objects.
Another option is to populate the relationship with a jpql fetch query:
"select survey from Surveys survey join fetch survey.responses"
I had the same problem and still can't find out what is going wrong. In my case the parent entity was loaded by a jpql query, and so extending this provided a workaround
this link helped.
I set the collection back to lazy. And
Inside persistence class, within transaction after getting the resultset, I am now calling getResponses as:
List<CustomerSurvey> surveys = query.getResultList();
for (CustomerSurvey survey : surveys) {
Set<SurveyResponse> responses = survey.getResponses();
}
that populates the responses.