Cassandra - unable to parse list of Tuple with Java driver - java

I am trying to access Tuple data structure I have stored in Cassandra with Mapper. But, I am unable to. I haven't found any example online.
This is the table and data I have created.
cqlsh:test> CREATE TABLE test.test_nested (id varchar PRIMARY KEY, address_mapping list<frozen<tuple<text,text>>>);
cqlsh:test> INSERT INTO test.test_nested (id, address_mapping) VALUES ('12345', [('Adress 1', 'pin1'), ('Adress 2', 'pin2')]);
cqlsh:test>
cqlsh:test> select * from test.test_nested;
id | address_mapping
-------+----------------------------------------------
12345 | [('Adress 1', 'pin1'), ('Adress 2', 'pin2')]
(1 rows)
My mapped class(using lombok for builder, getter, setter):
#Builder
#Table(keyspace = "test", name = "test_nested")
public class TestNested {
#PartitionKey
#Column(name = "id")
#Getter
#Setter
private String id;
#Column(name = "address_mapping")
#Frozen
#Getter
#Setter
private List<Object> address_mapping;
}
My Mapper class:
public class TestNestedStore {
private final Mapper<TestNested> mapper;
public TestNestedStore(Mapper<TestNested> mapper) {
this.mapper = mapper;
}
public void insert(TestNested userDropData) {
mapper.save(userDropData);
}
public void remove(String id) {
mapper.delete(id);
}
public TestNested findByUserId(String id) {
return mapper.get(id);
}
public ListenableFuture<TestNested> findByUserIdAsync(String id) {
return mapper.getAsync(id);
}
}
I am trying to access data in a test method as follows:
#Test
public void testConnection2(){
MappingManager manager = new MappingManager(scyllaDBConnector.getSession());
Mapper<TestNested> mapper = manager.mapper(TestNested.class);
TestNestedStore testNestedStore = new TestNestedStore(mapper);
ListenableFuture<TestNested> fut = testNestedStore.findByUserIdAsync("12345");
Futures.addCallback(fut, new FutureCallback<TestNested>() {
#Override
public void onSuccess(TestNested testNested) {
}
#Override
public void onFailure(Throwable throwable) {
System.out.println("Call failed");
}
});
}
Bit, I am unable to access the tuple. I get this error:
java.lang.IllegalArgumentException: Error while checking frozen types on field address_mapping of entity com.example.model.TestNested: expected List to be not frozen but was frozen
at com.datastax.driver.mapping.AnnotationChecks.validateAnnotations(AnnotationChecks.java:73)
at com.datastax.driver.mapping.AnnotationParser.parseEntity(AnnotationParser.java:81)
at com.datastax.driver.mapping.MappingManager.getMapper(MappingManager.java:148)
at com.datastax.driver.mapping.MappingManager.mapper(MappingManager.java:105)
I have also tried with private List<TupleValue> address_mapping;. But of no use!
How do I access Tuple values through object mapper of cassandra?

You define address_mapping as list<frozen<tuple<text,text>>>, that is, a list of frozen tuple values. To communicate this to the MappingManager, you can use the #FrozenValue attribute.
TestNested should look like:
#Builder
#Table(keyspace = "test", name = "test_nested")
public class TestNested {
...
#Column(name = "address_mapping")
#Frozen
#Getter
#Setter
#FrozenValue
private List<Object> address_mapping;
}

For defining the cassandra datatype of
map<text,frozen<tuple<text,text,int,text>>>
in java entity class mention the datatype as,
import com.datastax.driver.core.TupleValue;
#FrozenValue
private Map<String,TupleValue> event_driven;

Related

How to reference a list of objects like that is not a DynamoDB table

I have a table with a string attribute that is my hask key and another attribute that is of type list, but when doing some operation whose query goes through this list an error is returned that the list object must have the #DynamoDBTable annotation but the object is not a table.
Error: "com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException: class com.beasu.appbeasu.adapter.db.entity.ParesEntity not annotated with #DynamoDBTable
Look:
#DynamoDBTable(tableName = "tb_01_pare")
#ToString
#EqualsAndHashCode
public class DataPareEntity {
private String codDist;
private List<PareEntity> pares;
#DynamoDBHashKey(attributeName = "cod_dist")
public String getCodDist() {
return codDist;
}
public void setCodDist(String codDist) {
this.codDist= codDist;
}
#DynamoDBAttribute(attributeName= "obt_lis_pares")
public List<ParesEntity> getPares() {
return pares;
}
public void setPares(List<PareceresEntity> pareceres) {
this.pareceres = pareceres;
}
}
#AllArgsConstructor
#NoArgsConstructor
#DynamoDBDocument
public class ParesEntity {
private String codDist;
private String numFun;
private String txtJus;
private String indDec;
private String dateHr;
} // getters and setters...
If anyone knows the reason for this problem and can let me know I would be very grateful.

Inner property is not automatically cast in JOOQ

I have table as below:
CREATE TABLE recipes
(
id INT AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
components JSON,
active BOOLEAN NULL DEFAULT TRUE,
PRIMARY KEY (id),
UNIQUE KEY (name)
)
CHARACTER SET "UTF8"
ENGINE = InnoDb;
I have created pojo class like below:
#JsonIgnoreProperties(ignoreUnknown = true)
public class CValueRecipeV2
{
#JsonProperty("components")
#JsonAlias("matcher.components")
#Column(name = "components")
#Valid
private List<CComponentV2> mComponents;
#JsonProperty("name")
#Column(name = "name")
private String name;
public List<CComponentV2> getComponents()
{
return mComponents;
}
public void setComponents(List<CComponentV2> mComponents)
{
this.mComponents = mComponents;
}
public String getName()
{
return mName;
}
public void setName(String mName)
{
this.mName = mName;
}
}
another class
#JsonIgnoreProperties(ignoreUnknown = true)
public class CComponentV2
{
#JsonProperty("shingle_size")
#JsonAlias("shingleSize")
#CShingleField
private Integer mShingleSize;
public Integer getmShingleSize()
{
return mShingleSize;
}
public void setmShingleSize(Integer mShingleSize)
{
this.mShingleSize = mShingleSize;
}
}
Now I am trying to fetch the record from the database using JOOQ.
But I am not able to convert json component string into component class.
I am reading the data from the table as mentioned below:
context.dsl().select(RECIPES.asterisk())
.from(RECIPES)
.where(RECIPES.NAME.eq(name))
.fetchInto(CValueRecipeV2.class);
In the database, I have the following record.
ID name components active
1 a [{"shingle_size=2"}] true
While fetching the data, I am receiving the following error
Caused by: org.jooq.exception.DataTypeException: Cannot convert from {shingle_size=2} (class java.util.HashMap) to class com.ac.config_objects.CComponentV2
I am new to JOOQ. Please let me know if I missing anything.
Thanks in advance.
I have solved my problem using the jooq converter.
var record = context.dsl().select(RECIPES.asterisk())
.from(RECIPES)
.where(RECIPES.NAME.eq(name))
.fetchOne();
record.setValue(RECIPES.COMPONENTS, record.get(RECIPES.COMPONENTS, new CComponentV2Converter()));
var recipe = record.into(CValueRecipeV2.class);
and my converter lools like below:
public class CComponentV2Converter implements Converter<Object, List<CComponentV2>>
{
static final long serialVersionUID = 0;
#Override
public List<CComponentV2> from(Object databaseObject)
{
var componentList = CObjectCaster.toMapList(databaseObject);
List<CComponentV2> cComponentV2s = new ArrayList<>();
componentList.forEach(e -> {
CComponentV2 cComponentV2 = new CComponentV2();
cComponentV2.setmShingleSize(CObjectCaster.toInteger(e.get("shingle_size")));
cComponentV2s.add(cComponentV2);
});
return cComponentV2s;
}
}
jOOQ doesn't understand your #JsonProperty and other annotations out of the box. You will have to implement your own record mapper to support them:
https://www.jooq.org/doc/latest/manual/sql-execution/fetching/pojos-with-recordmapper-provider/

How to map List<UUID> to array with Hibernate?

I'm setting up a table in Postgres, and want to map List to jdbc array type using custom #Converter class. But I
get org.hibernate.MappingException: No Dialect mapping for JDBC type: 984991021
//StoredJob class for creating table:
#Entity
#Table(name = "jobs")
public class StoredJob {
....
//The error is here
#Column
#Convert(converter = JobFileListConverter.class)
private List<UUID> jobFiles;
//Converter class:
#Converter
public class JobFileListConverter implements
AttributeConverter<List<UUID>, UUID[]> {
#Override
public UUID[] convertToDatabaseColumn(List<UUID> uuidList) {
return uuidList.toArray(UUID[]::new);
}
#Override
public List<UUID> convertToEntityAttribute(UUID[] uuidArray) {
return Arrays.asList(uuidArray);
}
Change this:
private List<UUID> jobFiles;
with this one:
private UUID[] jobFiles;
But, I strongly suggest you to remove '#Convert' annotation and add a getter method as below:
public UUID[] getJobFiles() {
return jobFiles.stream().toArray(UUID[]::new);
}

Spring boot CrudRepository saves bad data

i have problem with saving data in DB.I'm new in Spring Boot. When i run my program the result of writen data is: packagename#randomcode example:com.abc.patient.Patient#6e3e681e
This is my Entity class - Patient.java
#Entity
public class Patient {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
// getter, setter, constructor, etc
}
This is my CrudRepo PatientRepository.java
public interface PatientRepository extends CrudRepository<Patient,Integer> {
}
This is my Service class PatientService.java
#Service
public class PatientService {
#Autowired
private PatientRepository patientRepository;
public void savePatient (String name) {
Patient patient = new Patient(name);
patientRepository.save(patient);
}
public Optional<Patient> showPatient(int id) {
return patientRepository.findById(id);
}
public List<Patient> showAllPatients() {
List<Patient> patients = new ArrayList<>();
patientRepository.findAll().forEach(patients::add);
return patients;
}
}
I think that problem in in the savePatient method in this line:
Patient patients = new Patient(name);
I checked the "name" parameter and it's in 100% correct String. I'm using Derby DB.
The only problem you have is how you are printing out your Patient class. Define a proper toString() or just debug yourself to see the resulting fields. There is no problem in your JPA implementation.
See this question for the details of default toString
Try:
public void savePatient(Patient patient) {
patientRepository.save(patient);
}

Java JPA "Error compiling the query" when it uses an enum

The following JPA query doesn't compile:
#NamedQuery(name = "PSA.findBySourceSystem",
query = "SELECT p FROM PSA p WHERE p.sourceSystem.id = :sourceSystemId")
p.sourceSystem is the following enum:
public enum SourceSystem {
FIRST(3, "ABC"), SECOND(9, "DEF"), THIRD(17, "GHI");
private int id;
private String code;
...
}
and is mapped in PSA's base class:
public class PsaBase implements Serializable {
#Column(name = "sourceSystemId")
#Enumerated(EnumType.ORDINAL)
protected SourceSystem sourceSystem;
...
}
The query compiles and runs fine if I replace p.sourceSystem.id in the query with something more benign.
Thank you in advance for any help.
It shouldn't compile.
You have to resolve the required enum value manually before passing it as a query parameter:
#NamedQuery(name = "PSA.findBySourceSystem",
query = "SELECT p FROM PSA p WHERE p.sourceSystem = :sourceSystem")
.
public enum SourceSystem {
...
private static Map<Integer, SourceSystem> valuesById = new HashMap<Integer, SourceSystem>();
static {
for (SourceSystem s: values())
valuesById.put(s.id, s);
}
public static SourceSystem findById(int id) {
return valuesById.get(id);
}
}
.
em.createNamedQuery("PSA.findBySourceSystem")
.setParameter("sourceSystem", SourceSystem.findById(sourceSystemId));
EDIT:
Since sourceSystem is annotated as #Enumerated(EnumType.ORDINAL), it's stored in the database as the ordinal numbers of the corresponding enum values, therefore FIRST is stored as 0. JPA doesn't directly support using arbitrary field of the enum value to identify it in the database. If your database schema assumes so, you can do the following trick to decouple state of your object from the database schema:
public class PsaBase implements Serializable {
protected SourceSystem sourceSystem;
#Column(name = "sourceSystemId")
public Integer getSourceSystemId() {
return sourceSystem.getId();
}
public void setSourceSystemId(Integer id) {
this.sourceSystem = SourceSystem.findById(id);
}
... getter and setter of sourceSystem with #Transient ...
}

Categories

Resources