Spring Boot: Postgres Character Varying column returns null - spring

I am trying to map an object of the following class to a Postgres table.
class MyClass {
private BigInteger id;
private String text;
//public setters and getters
}
I also have a table with 2 columns of type: bigint and character varying.
Then I am using a controller to query the db as shown below:
#GetMapping(value="/Resource")
public User getUser(#RequestParam BigInteger id) {
String sql = "SELECT \"ID\", \"TEXT\" FROM \"Table\" WHERE \"ID\"=" + id;
List<MyClass> objList = jdbcTemplate.query(sql,
BeanPropertyRowMapper.newInstance(MyClass.class));
}
While the id is retrieved correctly, the "text" field of the object is returned as null. Is it a datatype mismatch?

Related

Error - No Dialect mapping for JDBC type: 1111 while using Projection in JPARepository for jsonb type column

I have a jsonb column in my postgres db When I use findAll() method of JPA Repository to retrieve all data everything works like charm.
My Entity is as follows
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "steps")
public class Steps {
#EmbeddedId
private StepsId id;
#Column(name = "steps_name")
private String steps_name;
#Column(name = "sub_steps",columnDefinition = "jsonb")
#Convert(converter = SubStepsConverter.class)
private List<Substeps> sub_steps;
#Column(name = "status")
private String status;
}
When I use a Projection to retrieve selected data then it gives error No Dialect mapping for JDBC type: 1111
public interface StepsProjection {
String getid();
String getSteps_name();
#Convert(converter = SubStepsConverter.class)
List<Substeps> getSub_steps();
}
So if I remove List<Substeps> getSub_steps(); from above class and from my query everything works good so I guess the issue is with sub_steps field only which is a jsonb field while using Projection?
I have tried changing the Type to String in NotesProjection for substeps but no result.
I need to return only selected fields to the client.

issue saving record with Composite Key with one Generated value column : spring data jpa + DB2

i have a table in DB2 with name as policy this table has a composite primary key with columns : policy_id, context_cd.
policy_id is marked as always generated.
i am using spring boot with spring data jpa ,
Dialect i am using is org.hibernate.dialect.DB2Dialect in the properties file.
i have prepared the entity as below for the table policy
#Entity
#Data
#Table(name = "POLICY", schema = "...")
#IdClass(value = IdGenerationIdentity.class)
public class Policy {
// #EmbeddedId
// private IdGenerationIdentity idGenerationIdentity = new IdGenerationIdentity();
#Column(name="POLICY_ID", unique = true, nullable = false, insertable = false, updatable = false)
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long policyId;
#Column(name="CONTEXT_CD")
#Id
private String contextCd;
#Column(name="CASE_ID")
private Long caseId;
#Column(name="EMPLYR_GRP_ID")
private Long emplyrGrpId;
.....
}
Key class as below.
#Embeddable
public class IdGenerationIdentity implements Serializable {
private static final long serialVersionUID = -849058313293035312L;
// #GeneratedValue(strategy = GenerationType.IDENTITY)
//#NotNull
//#Column(name = "POLICY_ID")
//#Id
private Long policyId;
//#NotNull
//#Column(name = "CONTEXT_CD")
private String contextCd;
public IdGenerationIdentity(Long policyId, String contextCd) {
this.policyId = policyId;
this.contextCd = contextCd;
}
public IdGenerationIdentity() {
}
public Long getPolicyId() {
return policyId;
}
public void setPolicyId(Long policyId) {
this.policyId = policyId;
}
public String getContextCd() {
return contextCd;
}
public void setContextCd(String contextCd) {
this.contextCd = contextCd;
}
}
when i try to save to the DB using spring data jpa repository
policyRepository.save(policy);
i gives me an exception as below
ERROR org.springframework.boot.web.servlet.support.ErrorPageFilter - Forwarding to error page from request [/portalCase/createCase] due to exception [Error occurred while creating a new case. Error occurred while inserting policy.Could not set field value [POST_INSERT_INDICATOR] value by reflection : [class com.hmsy.pierws.portalCase.entity.IdGenerationIdentity.policyId] setter of com.hmsy.pierws.portalCase.entity.IdGenerationIdentity.policyId; nested exception is org.hibernate.PropertyAccessException: Could not set field value [POST_INSERT_INDICATOR] value by reflection : [class com.hmsy.pierws.portalCase.entity.IdGenerationIdentity.policyId] setter of com.hmsy.pierws.portalCase.entity.IdGenerationIdentity.policyId] java.lang.Exception: Error occurred while creating a new case. Error occurred while inserting policy.Could not set field value [POST_INSERT_INDICATOR] value by reflection : [class com.hmsy.pierws.portalCase.entity.IdGenerationIdentity.policyId] setter of com.hmsy.pierws.portalCase.entity.IdGenerationIdentity.policyId; nested exception is org.hibernate.PropertyAccessException: Could not set field value [POST_INSERT_INDICATOR] value by reflection : [class com.hmsy.pierws.portalCase.entity.IdGenerationIdentity.policyId] setter of com.hmsy.pierws.portalCase.entity.IdGenerationIdentity.policyId
another approach i have tried is using EmbeddedId. i have commented the same in the entity class above. when i use the embeddedId it gives me
rowid cannot be specified as a target column in insert

JPA Query for Column, Column has #Embedded Object

I'm writing JPA query and I have a Entity in side that Entity I have #Embedded Object, If I want to retrieve data based on the field in side #Embedded Object Can I write a JPA query instead of Named query?
Here is My Object structure :
public class MyEntity {
private String field1;
private String field2;
#Embedded
private InnerEntity;
}
#Embeddable
public class InnerEntity {
private String field3;
private String field4
}
Now I have to write a JPA query with field3 like how we do directly with field name (findByField1(value));
Any help appriciated
Try this :
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<MyEntity> root = cq.from(MyEntity.class);
Predicate p = cb.equal(root.get("InnerEntity").get("field3"), 100);
cq.multiselect(root.get("field1").alias("field1"),
root.get("InnerEntity").get("field3").alias("field3Alias));
List<Tuple> tt = em.createQuery(cq).getResultList();

MyBatis #Many / Spring-Boot

I'm beginner (sorry for my bad explanation, feel free to correct me) in MyBatis Spring-Boot, I have problem to understand and make it works #Many
I'm using 3 layer logic programming (Presentation Layer, Service Layer, Data Layer)
Thanks for your help :)
I have 3 Tables (it's TB_Products and not TB_Product as on the screenshot):
I would like to get data form table TB_Users and TB_Products to "put" it in DTO
I create 4 java object class SearchEntity, ProductEntity (for Data layer)
I create an interface SearchRepositoryMapper.
I also create a SearchService interface and SearchServiceImpl as well.
Java object class:
SearchEntity
public class SearchEntity implements Serializable{
private static final long serialVersionUID = -9143930742617602050L;
private String id;
private String firstName;
private String lastName;
private List<ProductEntity> products;
// Getters and Setters code .....
}
ProductEntity
public class ProductEntity implements Serializable{
private static final long serialVersionUID = -6525703679290992635L;
private String id;
private String productId;
private String product;
private String number;
private String date;
private String description;
// Getters and Setters code .....
}
SearchRepositoryMapper
public interface SearchRepositoryMapper {
// Get some fields from TB_Users and all fields from TB_Products
#Select("SELECT * FROM TB_Users WHERE id = #{id}")
#Results({
#Result(property = "id", column ="id"),
#Result(property = "firstName", column = "firstName"),
#Result(property = "lastName", column= "lastName"),
#Result(property = "products", javaType = List.class, column="id",
many = #Many(select = "getProductIdByUserId"))})
public SearchEntity findAllInfoByUserId(#Param("id") int id);
#Select("SELECT *, productId FROM TB_Products WHERE productId = #{id}")
public ArrayList<ProductEntity> getProductIdByUserId(#Param("id") int id);
// Find id by uderId and return null if it doesn't exist
#Select("SELECT id FROM TB_Users WHERE userId = #{userId}")
int findIdByUserId(#Param("userId") String userId);
}
SearchServiceImpl
#Service
public class SearchServiceImpl implements SearchService {
#Autowired
SearchRepositoryMapper searchRepository;
#Override
public SearchDto getAllInfoByUserId(String id) {
SearchDto returnValue = new SearchDto(); // Init returnValue as SearchDto
int searchId = searchRepository.findIdByUserId(id); // Init searchId with the TB_Users id
SearchEntity searchEntity = searchRepository.findAllInfoByUserId(searchId);
BeanUtils.copyProperties(searchEntity, returnValue);
return returnValue;
}
}
So when I execute the code and do a GET request I get this error message:
{
"message": "nested exception is org.apache.ibatis.executor.ExecutorException: Statement returned more than one row, where no more than one was expected."
}
I found out that come from the mapper and SearchEntity searchEntity = searchRepository.findAllInfoByUserId(searchId);
But i don't know how to resolve it. The way I wrote the code is wrong
Thanks to correct me
The exception clearly says that the query returns multiple results. Plese verify if the data in the table is correct.

MongoDB+Spring: Query Get Object without #DBRef referenceObjects

I am trying to query object without nested reference using Spring and mongo DB.
For instance
#Document
public class A {
#Id
private String id;
private String data;
#DBRef
private B b;
}
#Document
public class B {
#Id
private String id;
private String data;
}
I want to get A object without reference.
Querying A
public List<A> getAllA(String id) {
Query query = new Query();
query.addCriteria(Criteria.all());
List<A> aList = null;
aList = mongoOperations.findOne(query, A.class);
return aList;
}
Returns, I don't want to get nested b object:
[{
"_id": "AId..",
"data": "Adata..",
"b":{
"id":"BId..",
"data":"Bdata"
}
}]
Exclude fields.
Query query = new Query();
query.addCriteria(<query criteria>);
query.fields().exlude("b");

Categories

Resources